「这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战」
vue发布项目时经常会遇到服务器更新代码后,用户访问还是访问的老页面的问题,页面存在缓存,但是vue-cli默认打包的时候css和js都加了哈希值,所以每次修改后生成的文件名是不同的。那是为什么呢?
排查后才发现是因为入口index.html是没有版本号的,而服务器默认会对html页面进行缓存。
所以为了每次发布代码后,用户都能访问到最新代码,需要在服务器进行如下配置:
// vue-cli里的默认配置,css和js的名字都加了哈希值,所以新版本css、js和就旧版本的名字是不同的,不会有缓存问题。
// 但是把打包好的index.html放到服务器里去的时候,index.html在服务器端可能是有缓存的,这需要在服务器配置不让缓存index.html
// nginx 配置如下:
location = /index.html {
add_header Cache-Control "no-cache, no-store";
}
对hash过的静态文件还是采用默认方式,客户端会缓存。
对html文件,返回时增加头:Cache-Control,必须每次来服务端校验,根据etag返回200或者304
对应的nginx配置如下:
upstream example-be {
ip_hash;
server unix:/run/example-be.sock;
}
server{
listen 80; #监听端口
server_name example.com
# 后台api
location ~ ^/api {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
include uwsgi_params;
uwsgi_pass example-be;
}
# 前端静态文件
# 由于浏览器缓存静态文件的时间不可控,我们可以在nginx上自己配置expires 1M(1个月)
location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
root /var/www/example-fe/dist/;
expires 1M;
add_header Cache-Control "public";
}
# 前端html文件
location / {
# disable cache html
add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
root /var/www/example-fe/dist/;
index index.html index.htm;
try_files $uri /index.html;
}
}
|