Lazy Caching Proxy Results in Nginx

If you are using nginx as your front-end server for Django, you can also use it as a proxy cache (for smaller websites). You configure the cache like so:

proxy_cache_key "$scheme://$host$request_uri";
proxy_cache_path  /var/blog/cache  levels=1:2  keys_zone=blogcache:120m;
proxy_temp_path   /var/blog/proxy;
proxy_cache_valid 200 302  5m;
proxy_cache_valid 404      1m;
proxy_cache_use_stale updating;
proxy_cache_bypass $cookie_sessionid;
proxy_no_cache $cookie_sessionid;

The proxy_no_cache and proxy_cache_bypass lines tell nginx not to cache any pages which have a sessionid set (default name for Django session identifier cookie).  This assumes that you are using ssl-only cookies and you do not intend to cache anything from an authenticated user.  The effect for logged-in users is that they will always use the un-cached version, while the rest of the world will see updates only after the cache expires.  You can also include cache refreshing headers or the like, but this setup gets you a nice balance; you can handle requests for commonly requested pages quickly, and content is published within a few minutes of updating the database.


  1. tomcat

    tomcat on 07/02/2013 12:16 a.m. #

    how to determine a good value for blogcache and other param? E.g.

    proxy_cache_path /var/blog/cache levels=1:2 keys_zone=blogcache:120m;

Comments are closed.


Pingbacks are closed.