我使用位置部分以这种方式使用nginx为Angular 2应用程序提供服务:
location / {
try_files $uri $uri/ /index.html =404;
}
Run Code Online (Sandbox Code Playgroud)
try_files指令尝试在根目录中查找请求的uri,如果找不到它,则只返回index.html
如何禁用index.html文件的缓存?
Rem*_*Rem 29
使用nginx命名位置找到解决方案:
location / {
gzip_static on;
try_files $uri @index;
}
location @index {
add_header Cache-Control no-cache;
expires 0;
try_files /index.html =404;
}
Run Code Online (Sandbox Code Playgroud)
Dmi*_*sIr 16
location / {
try_files $uri $uri/ /index.html;
}
location = /index.html {
expires -1;
}
Run Code Online (Sandbox Code Playgroud)
您可以使用内容类型映射(应该使用一个文件完成 SPA 的工作.html):
map $sent_http_content_type $expires {
default off;
text/html epoch; # means no-cache
}
server {
expires $expires;
}
Run Code Online (Sandbox Code Playgroud)
我为我的 Angular 应用程序设置了以下设置,包括对 index.html 和 nginx 配置的更改:
索引.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" />
Run Code Online (Sandbox Code Playgroud)
配置文件
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;
}
Run Code Online (Sandbox Code Playgroud)
当用户导航到“site.com”和“site.com/some/url”或“site.com/#/login”时均可使用。“index.html”更改主要是为了安全起见。
感谢您的好评,雷姆!正如何世明指出的那样,在接受根目录(例如www.example.com/)时不会添加缓存头,但是在访问任何深层链接(例如www.example.com/some/path)时都不会添加缓存头。
经过大量的挖掘,我相信这是由于ngnix模块ngx_http_index_module的默认行为所致,默认情况下它包含index.html,因此在访问根目录/时,满足了第一个位置块的规则,并且没有使用缓存控制标头。我使用的解决方法是在第一个位置块中包含一个index指令而不指定index.html,从而强制从第二个位置块提供根/服务。
我还遇到另一个问题,我在第一个位置块中包含了根指令,该指令破坏了深层链接,也是一个坏主意。我将根指令移至服务器级别。
希望这会有所帮助,这是我的解决方案...
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我提供了调试标头,以帮助使其绝对清楚哪个位置块正在提供哪些内容。还要注意add_header指令的不直观行为,如果您还打算向位置块外部的所有请求添加标头,则必须阅读。
| 归档时间: |
|
| 查看次数: |
11812 次 |
| 最近记录: |