以vue为例,vue在打包的时候,css和js名字都加了哈希值,所以改动后打包生成的js和css是唯一的,页面请求的是新资源,不会有缓存问题。但是入口文件index.html会因为缓存造成更新问题,如果我们更新了,但是浏览器使用的是缓存,就会出现问题。所以需要对入口文件设置不使用强制缓存,需要每次去服务器验证文件是否修改,即使用协商缓存。
使用nginx反向代理,在nginx.conf文件的对应server中设置,目前我自己实践出的可行的一种写法是:
server {
listen 80;
server_name 域名;
root 文件目录;
index index.html;
location / { // 不加这一句,会出现nginx欢迎页面,无法正确加载资源
try_files $uri /index.html;
}
location ~ .*\.(html)$ { // 对html文件限制缓存
add_header Cache-Control no-store; // 不缓存
// 或者用add_header Cache-Control no-cache;替代上面那一句,协商缓存
add_header Pragma no-cache;
}
}
(1)Cache-Control: no-cache和Cache-Control: no-store区别
看字面意思容易误解,no-cache就是不缓存,但是no-cache并不是不缓存,而是使用协商缓存,所以并不能禁止缓存,no-store才是真正的禁止缓存。从节省带宽角度讲,使用no-cache更优一点,文件未发生改变时只传输很小的报文大小,只有在文件改变时才会传输整个文件大小。而不是no-store不管什么情况都传输整个文件大小。
(2)Pragma: no-cache:和Cache-Control: no-cache区别
Pragma: no-cache跟Cache-Control: no-cache相同,Pragma: no-cache兼容http 1.0 ,Cache-Control: no-cache是http 1.1提供的。因此,Pragma: no-cache可以应用到http 1.0 和http 1.1,而Cache-Control: no-cache只能应用于http 1.1.
参考文章