Nginx proxy_cache_bypass fastcgi_cache_bypass proxy_no_cache dont cache logged in users
Written by somer orbay
|
07 September 2011

Content caching, its the most used way to speed up the dynamic or static pages on a website but what happens if you want to have your visitors see the cached content and logged in users (Members) to have the content from the backend server (Non cached), here comes the fastcgi_cache_bypass - fastcgi_no_cache or proxy_cache_bypass - proxy_no_cache.
in order to apply this, you need to find out which cookies your script sets when a user logs in, in my case the cookie was "mnm_key" so i used this location block to seperate guests and members from caching.
location / {
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_pass http://here-comes-the-ip-or-domain;
proxy_no_cache $cookie_mnm_key;
proxy_cache_bypass $cookie_mnm_key;
proxy_pass_header "Set-Cookie";
proxy_pass_header "Cookie";
proxy_ignore_headers "Cache-Control" "Expires";
proxy_cache_key $uri$is_args$args;
proxy_cache proxy_buzz;
proxy_cache_use_stale updating error timeout invalid_header http_500;
proxy_cache_valid 200 5m;
proxy_cache_valid 303 302 1s;
error_page 502 503 /usr/local/www/nginx-dist/50x.html;
}
Notice that i used only 5 minutes for the cache refresh interval, thats because my site gets updated oftenly and frontpage needs to be recent. If your site is getting updated daily you can use 1d for the valid 200 response.
Now, for guests the site is cached for 5 minutes and members see no cached content as they are being served directly from the backend.