【发布时间】:2017-05-28 15:15:43
【问题描述】:
我以这种方式使用位置部分通过 nginx 为 Angular 2 应用程序提供服务:
location / {
try_files $uri $uri/ /index.html =404;
}
try_files 指令尝试在根目录中查找请求的 uri,如果找不到,则简单地返回 index.html
如何禁用 index.html 文件的缓存?
【问题讨论】:
我以这种方式使用位置部分通过 nginx 为 Angular 2 应用程序提供服务:
location / {
try_files $uri $uri/ /index.html =404;
}
try_files 指令尝试在根目录中查找请求的 uri,如果找不到,则简单地返回 index.html
如何禁用 index.html 文件的缓存?
【问题讨论】:
找到使用 nginx 命名位置的解决方案:
location / {
gzip_static on;
try_files $uri @index;
}
location @index {
add_header Cache-Control no-cache;
expires 0;
try_files /index.html =404;
}
【讨论】:
/index.html结尾的URL),只是不要将index指令放在location /中
感谢雷姆的精彩回答!正如何世明用公认的解决方案指出的那样,在访问根目录时不会添加缓存标头,例如www.example.com/,但在访问任何深层链接时都会被添加,例如www.example.com/some/path.
经过大量挖掘,我相信这是因为ngnix模块ngx_http_index_module的默认行为,它默认包含index.html,所以在访问根/时,第一个位置块的规则被满足,并且index.html。 html 在没有缓存控制标头的情况下提供。我使用的解决方法是在第一个位置块中包含一个 index 指令而不指定 index.html,从而强制从第二个位置块提供根 /。
我还有另一个问题,我在第一个位置块中包含了一个根指令,它破坏了深层链接,也是一个bad idea。我将根指令移至服务器级别。
希望这有帮助,这是我的解决方案...
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
location / {
add_header X-debug-whats-going-on 1;
index do-not-use-me.html;
try_files $uri @index;
}
location @index {
add_header X-debug-whats-going-on 2;
add_header Cache-Control no-cache;
expires 0;
try_files /index.html =404;
}
}
我已经包含了调试标头,以帮助明确哪个位置块正在提供什么内容。同样值得注意的是unintuitive behaviour of the add_header directive,如果您还打算将标头添加到位置块之外的所有请求,则必须阅读。
【讨论】:
location / 中删除index 指令?
location / {
try_files $uri $uri/ /index.html;
}
location = /index.html {
expires -1;
}
【讨论】:
以下设置适用于我的 Angular 应用程序,包括对 index.html 和 nginx 配置的更改:
index.html
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" />
<meta http-equiv="pragma" content="no-cache" />
nginx.conf
location / {
try_files $uri $uri/ /index.html;
}
location ~ \.html$ {
add_header Cache-Control "private, no-cache, no-store, must-revalidate";
add_header Expires "Sat, 01 Jan 2000 00:00:00 GMT";
add_header Pragma no-cache;
}
当用户导航到“site.com”和“site.com/some/url”或“site.com/#/login”时都有效。 “index.html”更改主要是为了安全起见。
【讨论】:
您可以使用内容类型映射(应该使用一个 .html 文件来完成 SPA 的工作):
map $sent_http_content_type $expires {
default off;
text/html epoch; # means no-cache
}
server {
expires $expires;
}
【讨论】:
为了安全起见:)
location = /index.html {
add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
expires off;
}
【讨论】: