仅为所选文件定义特定的缓存控制标头

时间:2019-07-10 04:10:14

标签: nginx gatsby cache-control

我正在为Gatsby设置Nginx服务器(版本1.17.1),并按照https://www.gatsbyjs.org/docs/caching/的建议进行操作。

下面的代码段是我的server {}块尝试实现建议的缓存配置的部分;

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

同样用if statement代替location {}块来为服务工作程序文件sw.js定义缓存配置,如下所示;

if ($request_uri ~ ^sw\.(?:js)$) {
    set $no_cache 1;
}

不幸的是,除sw.js以外,所有文件都已按预期成功缓存。

我在做什么错了,该如何解决,以便有效地将sw.js的缓存控制标头设置为public, max-age=0, must-revalidate

2 个答案:

答案 0 :(得分:2)

https://nginx.org/en/docs/http/ngx_http_core_module.html#location

中描述了location的优先顺序

找到精确匹配项(使用=修饰符时,搜索将终止,并且不检查正则表达式,因此可以将其用于sw.js

location = /sw.js {
    add_header Cache-Control "public, max-age=0, must-revalidate";
}

答案 1 :(得分:0)

我最终得到了有关Gatsby.js缓存的以下nginx配置:

        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:您最终采用哪种配置?毕竟,您也许可以编辑此答案以匹配完美的解决方案。用于搜索“正在缓存nginx gatsby”的人。

相关问题