4

我正在为 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 语句代替location {}用于定义服务工作者文件的缓存配置的块sw.js,如下所示;

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

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

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

4

2 回答 2

6

我最终得到了以下关于 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”的人。

于 2019-09-25T05:39:52.997 回答
4

location这里描述的优先顺序https://nginx.org/en/docs/http/ngx_http_core_module.html#location

当找到完全匹配(使用=修饰符)时,搜索终止并且不会检查正则表达式,因此您可以将其用于您的sw.js

location = /sw.js {
    add_header Cache-Control "public, max-age=0, must-revalidate";
}
于 2019-07-10T09:50:47.747 回答