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

nye*_*eke 4 nginx cache-control gatsby

我正在为 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";
}
Run Code Online (Sandbox Code Playgroud)

同样尝试使用if 语句代替location {}为 service worker 文件定义缓存配置的块sw.js,如下所示;

if ($request_uri ~ ^sw\.(?:js)$) {
    set $no_cache 1;
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,除了sw.js.

我在做什么错了,我怎么能解决这个问题,从而有效一套高速缓存控制报头sw.jspublic, max-age=0, must-revalidate

Rob*_*uch 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";
        }
Run Code Online (Sandbox Code Playgroud)

@OP:您最终采用哪种配置?也许您可以编辑此答案以匹配完美的解决方案;对于搜索“缓存 nginx gatsby”的人。