'nginx: disable cache for everything except all png/svg and one js file
I'm using nginx to serve a documentation website that changes frequently. For this reason I decided to drop cache with the following:
add_header Last-Modified $date_gmt;
add_header Cache-Control 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
if_modified_since off;
expires off;
etag off;
proxy_no_cache 1;
proxy_cache_bypass 1;
However with this, for each page you are visiting on this site, it downloads each time an big js file (7mb) and all png/svg images, so I would like to drop cache for everything except for all png/svg and one js file that resides in the ROOT path of the project. Is possible with nginx?
Solution 1:[1]
Since you don't use the proxy_pass directive, tuning proxy_no_cache and proxy_bypass parameters makes no sense, you can safely remove that part from you config. For everything else the following should be enough to cache only selected files while do not cache everything else.
This should be placed to the http context:
map $uri $cacheable {
~\.(?:pn|sv)g$ 1;
/script.js 1;
}
map $cacheable $cache_control {
1 "public, max-age=31536000";
default "no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0";
}
map $cacheable $expire {
1 1y;
default off;
}
This should be placed at the server context instead of your current configuration snippet:
add_header Cache-Control $cache_control;
expires $expire;
And take a look at this answer to not be surprised with add_header directive behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivan Shatsky |
