Page-level caching with Nginx

Since my last post on using Nginx to cache proxied content, they have added proper cache handling via their proxy_cache* directives. These are much more suitable for use, as they capture the HTTP response headers and also use more advanced Cache-Control checks.

To start, install the latest stable Nginx avaliable at .

Next edit your nginx.conf and add the proxy_cache_path directive to define a named cache storage. These are independant of servers and locations, and can be reused inside each later on.

http {
    proxy_cache_path /var/cache/nginx keys_zone=anonymous:10m;
    include vhosts/*.conf

Next create the directory for the cache:

mkdir -p /var/cache/nginx

Next define your server configuration, which can be done for example in conf/vhosts/ if you defined the include above.

server {
    listen            80;
    proxy_set_header  X-Real-IP  $remote_addr;
    proxy_set_header  Host       $host;
    location / {
        proxy_pass    http://localhost:8080/;
        proxy_cache   anonymous;
    # don't cache admin folder, send all requests through the proxy
    location /admin {
        proxy_pass    http://localhost:8080/;
    # handle static files directly. Set their expiry time to max, so they'll
    # always use the browser cache after first request
    location ~* (css|js|png|jpe?g|gif|ico)$ {
        root          /var/www/${host}/http;
        expires       max;

As we don’t want the nginx worker processes to have root permissions when in use, add to the start of conf/nginx.conf:

user nginx

Then sort out the user and permissions:

useradd nginx
chown nginx:nginx /var/cache/nginx /usr/local/nginx/{fastcgi_temp,logs,proxy_temp}

To start nginx on bootup, add the following to the end of /etc/rc.local:


Then also run this command to start nginx now.

That is all that is needed, no patches this time. There are several more proxy_cache* directives avaliable that you can use to tweak its behaviour, see the proxy module documentation for more details.