I'm setting up a Nginx sever (version 1.17.1) for Gatsby following up the recommendation at https://www.gatsbyjs.org/docs/caching/.
The snippet below is the portion my server {}
block attempting implementing the recommended caching configuration;
location ~* \.(?:html)$ {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
location /static {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location ~* \.(?:css|js)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location /sw\.js {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
Equally tried an if statement in place of the location {}
block for defining cache configuration for the service worker file, sw.js
, as below;
if ($request_uri ~ ^sw\.(?:js)$) {
set $no_cache 1;
}
Unfortunately, all files get cached successfully as expected except sw.js
.
What am I doing wrong and how can I fix it so as to effectively set cache control header for sw.js
to public, max-age=0, must-revalidate
?
I ended up with the following nginx configuration regarding caching for Gatsby.js:
location ~* \.(?:html)$ {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
location /page-data {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
location = /sw.js {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
location /static {
add_header Cache-Control "public, max-age=31536000, immutable";
}
location ~* \.(?:js|css)$ {
add_header Cache-Control "public, max-age=31536000, immutable";
}
@OP: With which configuration did you end up? Maybe you can edit this answer to match the perfect solution after all; for people searching for "caching nginx gatsby".
The order of precedence of location
is described here https://nginx.org/en/docs/http/ngx_http_core_module.html#location
When an exact match is found (using the =
modifier) the search terminates and regular expressions will not be checked, so you can use that for your sw.js
:
location = /sw.js {
add_header Cache-Control "public, max-age=0, must-revalidate";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With