Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nginx: Punching a Hole Through My Cache Not Working as Expected

I have a single page app and am trying to use the query parameter nocahce=true to bypass Nginx cache for the first response (HTML file) and ALL subsequent requests initiated by it (to get CSS, JS, etc).

According to this, I can bypass my cache using the query parameter but it is not working as expected.

Steps to reproduce the issue:

Use this minified generic configuration:

http {
    ...
    proxy_cache_path /var/temp/ levels=1:2 keys_zone=STATIC:10m inactive=24h max_size=1g;
    server {
        ...
        location / {
            # Using angularjs.org as an example
            proxy_pass https://angularjs.org;
            proxy_set_header Host angularjs.org;

            proxy_cache STATIC;
            proxy_cache_valid 200 10m;
            proxy_cache_bypass $arg_nocache;
            add_header X-Cache-Status $upstream_cache_status always;
        }
    }
}

Expected:

The response header of the requests "http://servername" and "http://servername/css/bootstrap" (or any other subsequent requests initiated by http://servername?nocache=true) to bypass the cache, i.e. contain "X-Cache-Status: BYPASS".

Actual:

The response header of "http://servername" contains "X-Cache-Status: BYPASS" but "http://servername/css/bootstrap" does not, instead the value of "X-Cache-Status" is HIT/MISS/etc depending on the cache status.

Am I using the proxy_cache_bypass in a wrong way or do I need to do more to achieve the expected behavior?

Thanks!

like image 242
Amri Avatar asked Sep 06 '25 03:09

Amri


1 Answers

I was able to solve this by using cookie_nocache.

Update the directive proxy_cache_bypass to:

proxy_cache_bypass $cookie_nocache;

If you need to bypass the cache, set a cookie named "nocache" to true (any value that isn't empty nor 0 will work). Since the browser will send the cookies to subsequent requests, this will work.

To quickly test this, open the console and add the cookie like this.

document.cookie="nocache=true"

like image 114
Amri Avatar answered Sep 09 '25 10:09

Amri