Define specific cache control header for selected file only

巧了我就是萌 提交于 2019-12-10 11:44:50

问题


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?


回答1:


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";
}



回答2:


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



来源:https://stackoverflow.com/questions/56963293/define-specific-cache-control-header-for-selected-file-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!