如何在nginx上设置html不缓存

4,560 阅读1分钟

一、简介

前端项目发布以后,经常会遇到访问不到最新的版本,这主要是由于我们项目的入口文件index.html被浏览器或者代理缓存了,没有实时拉取到最新文件。本文将介绍一下在nginx上如何设置html文件不缓存。

二、Cache-Control介绍

2.1 服务器可以在响应中使用的标准 Cache-Control 指令。

Cache-control: must-revalidate
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: public
Cache-control: private
Cache-control: proxy-revalidate
Cache-Control: max-age=<seconds>
Cache-control: s-maxage=<seconds>

2.2 配置示例

2.2.1 禁止缓存

发送如下响应头可以关闭缓存。此外,可以参考ExpiresPragma消息头。

Cache-Control: no-store

2.2.2 缓存静态资源

对于应用程序中不会改变的文件,你通常可以在发送响应头前添加积极缓存。这包括例如由应用程序提供的静态文件,例如图像,CSS 文件和 JavaScript 文件。另请参阅 Expires 标题。

Cache-Control:public, max-age=31536000

2.2.3 需要重新验证

指定 no-cache 或 max-age=0, must-revalidate 表示客户端可以缓存资源,每次使用缓存资源前都必须重新验证其有效性。这意味着每次都会发起 HTTP 请求,但当缓存内容仍有效时可以跳过 HTTP 响应体的下载。

Cache-Control: no-cache
Cache-Control: max-age=0, must-revalidate

注意: 如果服务器关闭或失去连接,下面的指令可能会造成使用缓存。

Cache-Control: max-age=0

三、nginx配置

location / {
 expires 1h;
 root /home/html;
 index index.html index.htm;

 ## html不缓存 
 if ($request_filename ~* .*\.(htm|html)$) 
 {
     add_header Cache-Control "no-store";
 }
}

image.png