一、简介
前端项目发布以后,经常会遇到访问不到最新的版本,这主要是由于我们项目的入口文件index.html被浏览器或者代理缓存了,没有实时拉取到最新文件。本文将介绍一下在nginx上如何设置html文件不缓存。
二、Cache-Control介绍
强缓存、协商缓存、无缓存区别
强缓存:浏览器不与服务端协商直接取浏览器缓存
协商缓存:浏览器会先向服务器确认资源的有效性后才决定是从缓存中取资源还是重新获取资源
无缓存:浏览器直接向服务器重新获取资源
三种缓存机制皆通过配置http头(add_header)的Cache-Control来实现。强缓存还可以使用Expires字段实现。
Expires:response header里的过期时间,浏览器再次加载资源时,如果在这个过期时间内,则命中强缓存(http1.0的产物,现在一般用cache-control)。cache-control的优先级高于expires,expires是http1.0的产物,而cache-control是http1.1的产物,两者同时存在的时候expire会被cache-control的max-age覆盖,在不支持http1.1的情况下可能就需要expires来保持兼容。
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>
三、nginx缓存配置示例
location / {
expires 1h;
root /home/html;
index index.html index.htm;
# 所有资源不缓存
add_header Cache-Control no-cache;
# 强缓存时间配置,5分钟内再次请求则直接使用浏览器缓存
add_header Cache-Control max-age=300;
## html不缓存
if ($request_filename ~* .*\.(htm|html)$)
{
add_header Cache-Control "no-store";
}
}