This tutorial shows how to configure nginx as a reverse proxy cache.

This configuration will contain the following elements:

Cache at the level of reverse proxy
Activation of the fields expires in the http request
Compression between the client and the reverse proxy
Limiting connections between the client and the reverse proxy (number and time)


Read the documentation on Nginx page: asynchronous Web server.
Understand the function of a reverse proxy or a proxy reverse wikipedia Article.


Some present terms in this article are not very “academic” feel free to modify them if you know.

The configuration that will follow will break down into three parts:

The overall setup of the nginx Server.
The setting of functions of reverse proxy and cache.
An example of configuration of the web server located behind the reverse proxy.

Files and configuration files used will be:

/ etc/nginx/sites-enabled /
/ etc/nginx/sites-available /.

This separation is intended to add clarity in the configuration because all configuration files are included in the nginx.conf file.
Global configuration of the server

The configuration is done in the file /etc/nginx/nginx.conf

Contents of the file

user www – data.
worker_processes 1;
error_log var/log/nginx/error.log;
PID var/run/nginx.pid;
events {}
worker_connections 1024;
http {}
include etc/nginx/mime.types;
DEFAULT_TYPE application/octet-stream;
access_log var/log/nginx/access.log;
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
tcp_nodelay on;
# envoi moins d’information sur le serveur
server_tokens off;

# taille des buffers et taille max des requêtes normales
client_body_buffer_size 1b;
client_max_body_size 8m;
large_client_header_buffers 1 1b;
ignore_invalid_headers on;

# définition des différents timeout
client_body_timeout 5;
client_header_timeout 5;
keepalive_timeout 5 5;
send_timeout 5;
ignore_invalid_headers on;
server_name_in_redirect off;

# active la compression des pages sauf pour les navigateurs pourris
gzip on;
gzip_comp_level 6;
gzip_proxied any;
gzip_vary on;
gzip_types text/plain text/css application/x-javascript;
gzip_disable “MSIE [1-6] \. (?!. * SV1) “;

# limitation du nombre de connexion par client
limit_zone gulag $binary_remote_addr 1m;
limit_conn gulag 50;


Clear All
user with which will be launched the process, the ci must have the least privileges possible
worker_processes is the number of hearts
worker_connections set this parameter according to the above calculation below (valid only on a reverse proxy) max_clients = worker_processes * worker_connections/4
access_log connections log file path
error_log path to the error log file
DEFAULT_TYPE type default files whose type is not listed in the entries file
server_tokens off allows to disclose less information on the reverse proxy
client_body_buffer_size sets the size beyond which the query will be saved to a file
client_max_body_size size max of data sent by a client
large_client_header_buffers sets the number of buffer as well as their sizes, the size is max in the URI query so the multiplication of these two figures
client_body_timeout if the client does not send all of its application in 5 sec it is dead!
client_header_timeout if the client does not send the header of its application same treatment
keepalive_timeout 5 5 first digit time max of a keepalive connection, second digit indication of this value in the timeout field of the response header
keepalive_requests 100 number of requests on a connection keepalive
send_timeout maximum time of latency when a sending
ignore_invalid_headers removes the malformed requests
server_name_in_redirect disables the rewrite of the server name, protection from scans
enabling or disabling compression gzip
gzip_comp_level compression level (can go up to 9)
gzip_proxied any enable compression for the response from the web server behind reverse proxy
active gzip_vary http “Vary: Accept – Encoding” header
gzip_types file types which will be compresses
gzip_disable allows disabling of compression for rotten browsers
limit_zone gulag $binary_remote_addr 1 m creates a storage area named ‘gulag’ using less than 1 MB of RAM, containing the State of the connections by ip address
limit_conn gulag 50 limits the number of connections parallel to 50 per client request
Functions setting reverse proxy and cache

Parameters of reverse proxy and cache will be logged in the file /etc/nginx/conf.d/proxy.conf for clarity.

If you want more information about the configuration of the proxy, go see the official documentation here.

Contents of the file

proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_hide_header X-Powered-By;
proxy_intercept_errors on;
proxy_buffering on;

proxy_cache_key “$scheme: / / $host$ request_uri”;
proxy_cache_path/var/cache/nginx levels = 1:2 keys_zone = cache: 10 m inactive = 7 d max_size = 700 m;

options explanations
proxy_redirect off allows a rewrite of the address, useless when the web server is not located on the same physical machine
proxy_set_header allows to modify headers
proxy_hide_header allows to hide some headers
proxy_intercept_errors allows you to control returns error code from the web server and modify in the stolen
proxy_buffering on if we disable this option rear server must wait for the data to be sent to the client to close its connection with nginx
proxy_cache_min_uses 3 the resource must be requested 3 times before cacheable
proxy_cache_key key for storing files from several different sites in the same cache. The file names will be the md5 of this combination
proxy_cache_path specifies the path to the cache folder, organization of the files (if anyone has more information on this directive, its participation is welcome)
level 1:2 indicates the Organization of the files,
keys_zone sets the name of this inactive zone sets the maximum of an item retention time unless it is requested by a client. If the time limit is exhausted the item is deleted,
max_size indicates the maximum size of the cache
Example of configuring a web server back

We will create the file trucbidule in the directory/etc/nginx/sites-available /.

The configuration items:

arriving on port 80, and requests for domain name of destination trucbidul.fr will be redirected to the web server having the address of
only GET, HEAD, and POST methods will be accepted
all files will be cached minimum 12 hours
static files are cached 2 days
No caching for the administration section of the site
the fields expires http request will be filled
error codes will be intercepted and a page will be returned

Contents of the trucbidule file:

Server {}

listen 80;
server_name www.trucbidule.fr trucbidule.fr;

# Here on disables the access_log to duplicate with Apache
access_log off;
#access_log var/log/nginx/default.access.log;

If ($request_method! ~ ^ (GET|) HEAD| (POST) $) {}
return 444;

rental / {}
proxy_cache cache;
proxy_cache_valid 12 h;
expires 12: 00;
proxy_cache_use_stale error timeout invalid_header updating;

rental ~*^.+(swf|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|
BMP|RTF|js) $ {}
proxy_cache cache;
proxy_cache_valid 2d;
expires max;

location ^ ~ (^ / admin| ^ / identification) {}

error 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 500 501 502 503 504 505 506 507 error.html;

location = error.html {}
root /var/ www/nginx-default;

options explanations
listen address and port to listen, here he listens on all addresses
server_name domain name back server, possibility to specify several
error redirection of the following errors to the specified path
proxy_pass indicates the address of the web server back
proxy_cache_valid 12 h all returning with a code 200 301 and 302 pages will be stored in cache for 12 hours. It is possible to specify the html codes for which files should be cached
proxy_cache indicates the storage area for the cache
proxy_cache_use_stale if the server rear reference these errors error timeout invalid_header updating nginx will serve the files that it has cached
expires max gives a maximum expiration date so that the client can update the static files caching

Some explanations on our configuration. As you’ve seen all requests are not processed in the same way. Different rules were created to separate the content.

If the address begins with a / (IE all the time) the elements are cached for 12 h.
If the address ends with one of the listed file extensions, then the elements are cached for 2 days.
If the address begins with/admin or/Government there’s no caching.
If the address matches error.html then a local file is served.

As you can get account in some cases several rules are met. There is a hierarchy among these rules. The official documentation covers this topic here.

To summarize, here is the hierarchy:

= When the address is exactly the same the condition is met and the other rules are not checked.
^ ~ When the address begins with the expression other rules are not checked.
~ Regular expressions are analysed in their order of appearance in the file.
Finally rule rental / corresponding to all cases is applied in the case where address not met the conditions of the preceding rules.

You may have noticed in the configuration file a little star after the wave ~ *. This indicates that the rule is not a case-sensitive.

It is sufficient to activate the server, create a symbolic link pointing to the previous file in the directory:

sudo ln-s/etc/nginx/sites-available/trucbidule/etc/nginx/sites-enabled/trucbidule

Load balancing

It is possible to do load balancing with nginx in a fairly simple manner. It is sufficient to declare a group of servers and send queries to this group of hosts with the proxy_pass directive. The official documentation detailing the procedure as well as all possible options is available here.

Here is the example of the official documentation:

upstream backend {
server backend1.example.com weight=5;
server backend2.example.com:8080;
server unix:/tmp/backend3;

server {
location / {
proxy_pass http://backend;