如何仅为根路径配置缓存响应标头?

发布于 2025-01-22 01:44:59 字数 284 浏览 1 评论 0原文

我正在使用nginx作为静态文件,并希望所有文件应由浏览器缓存,而不是index.html。尝试了以下配置,但我还获得了index.html的高速缓存响应标头。 如何更改配置?

server{
  location = / {
   try_files $uri $uri/ =404;
  }
  location / {
   try_files $uri $uri/ =404;
   add_header 'Cache-Control' "public, max-age=3600";
  }
}

i am using nginx for static files and want that all files should be cached by browser, but not index.html. Tried following config but i get cache response header for index.html also.
how can i change config?

server{
  location = / {
   try_files $uri $uri/ =404;
  }
  location / {
   try_files $uri $uri/ =404;
   add_header 'Cache-Control' "public, max-age=3600";
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我不是你的备胎 2025-01-29 01:44:59

要了解try_files $ uri $ uri/...指令(和整个nginx行为)的逻辑,我建议您阅读在ServerFault上回答。重要的是

非常重要但绝对不太明显的事情是index try_files $ uri $ uri/= 404可能会导致内部重定向。。 P>

这就是您当前的配置发生的情况。 $ uri/ try_files指令的参数使Nginx从/ /Index.html / >,然后由location / {...} < / code>来处理URI,而不是location = / {...} < / code>!为了实现所需的目标

location = /index.html {
    try_files $uri $uri/ =404;
}
location / {
    try_files $uri $uri/ =404;
    add_header 'Cache-Control' "public, max-age=3600";
}

,您可以使用此外

location = /index.html {}
location / {
    add_header 'Cache-Control' "public, max-age=3600";
}

To understand the logic of try_files $uri $uri/ ... directive (and the whole nginx behavior) I recommend you to read this answer at ServerFault. The essential thing is

The very important yet absolutely non-obvious thing is that an index directive being used with try_files $uri $uri/ =404 can cause an internal redirect.

This is what happens with your current config. The $uri/ argument of the try_files directive causes nginx to make an internal redirect from / to /index.html, and that URI in turn is processed by the location / { ... }, not the location = / { ... }! To achieve what you want you can use

location = /index.html {
    try_files $uri $uri/ =404;
}
location / {
    try_files $uri $uri/ =404;
    add_header 'Cache-Control' "public, max-age=3600";
}

Moreover, since the try_files $uri $uri/ =404; is default nginx behavior, you can further simplify it to

location = /index.html {}
location / {
    add_header 'Cache-Control' "public, max-age=3600";
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文