Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define specific cache control header for selected file only

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?

like image 817
nyedidikeke Avatar asked Dec 22 '22 22:12

nyedidikeke


2 Answers

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".

like image 55
Robin Wieruch Avatar answered May 16 '23 08:05

Robin Wieruch


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";
}
like image 34
Dusan Bajic Avatar answered May 16 '23 07:05

Dusan Bajic