Nginx – Configure nginx for max-age=0 requests

cachehttpnginxreverse-proxy

I'm using nginx as a reverse proxy with proxy_cache. The back-end is setting cache-control response headers which makes nginx serve responses from cache when possible.

However I would like to allow clients to bypass the cache by setting a request header Cache-Control:max-age=0. This way users can get a fresh copy by hitting CTRL+R in browser. By default, nginx seems to ignore the Cache-Control request header.

How can I configure nginx to fetch a fresh copy from the back-end and update the cache whenever a client requests a resource with Cache-Control:max-age=0?

Best Answer

You could use proxy_cache_bypass.

proxy_cache_bypass  $http_cache_control;

This will cause nginx to fetch a fresh copy of the document in the presence of the Cache-Control header in the HTTP request from the client.

Note that the resulting response from the backend is still eligible for caching. If you want to disqualify it from being cached, use the same arguments with the proxy_no_cache directive, too.

Source: http://wiki.nginx.org/HttpProxyModule#proxy_cache_bypass


If you specifically want to only bypass the cache when the client has Cache-Control: max-age=0 in the headers (e.g. to explicitly not support another variant, Cache-Control: no-cache, which is actually supposedly a stronger preference for a fresh copy of the page than max-age=0 is), then you can use the following, which I won't recommend due to such limitation:

set $cc_ma  0;
if ($http_cache_control = "max-age=0") {    # honour ⌘R, ignore ⇧⌘R (yes, bad idea!)
    set $cc_ma  1;
}
proxy_cache_bypass  $cc_ma;

BTW, there's also Pragma: no-cache, which this obviously won't account for, although in my limited set of experiments, it's always accompanied by a Cache-Control: no-cache, so, the original one-liner would probably do the best job.

As a note, SeaMonkey sends Cache-Control: max-age=0 when you click Reload or ⌘R, and Pragma: no-cache\r\nCache-Control: no-cache when you Shift Reload or ⇧⌘R.

Related Topic