Vue项目打包部署Nginx配置及前端缓存问题解决
配置如下其中:/app 是网站根目录3、缓存问题解决浏览器缓存分类:html默认当做了静态文件传输,会被浏览器缓存,每次打开都拿不到最新的页面使用Charles抓包发现:访问网站首页压根没有进行请求,直接从浏览器本地获取了index.html文件。看来浏览器使用了强制缓存策略nginx 添加以下配置,告诉浏览器怎么缓存html文件参数说明Cache-Control: no-cache协商缓存,只能
·
1、部署单个站点
配置如下
server {
listen 80;
server_name localhost;
location / {
root /app;
index index.html;
try_files $uri $uri/ /index.html;
}
}
其中:
/app 是网站根目录
2、部署多个站点
server {
listen 80;
listen 443 ssl http2;
server_name www.demo.com;
if ($ssl_protocol = "") { return 301 https://$host$request_uri; }
# 前端
location / {
root /data/wwwroot/www;
index index.html;
try_files $uri $uri/ /index.html;
}
# 后台
location ^~/admin {
alias /data/wwwroot/admin;
try_files $uri $uri/ /admin/index.html;
}
# 数据接口
location /api {
proxy_pass http://127.0.0.1:5000;
}
}
3、缓存问题解决
浏览器缓存分类:
- 强制缓存
- Expires:依赖本地时间和服务器时间
- Cache-control:max-age=10
- 协商缓存
- last-modified:文件修改时间
- ETag:文件指纹
- 禁用缓存
- Cache-control:no-store
html默认当做了静态文件传输,会被浏览器缓存,每次打开都拿不到最新的页面
使用Charles抓包发现:
访问网站首页压根没有进行请求,直接从浏览器本地获取了index.html文件。看来浏览器使用了强制缓存策略
nginx 添加以下配置,告诉浏览器怎么缓存html文件
# 对html文件限制缓存
location ~ .*\.(html)$ {
# 不缓存
# add_header Cache-Control no-store;
# 或者用 协商缓存
add_header Cache-Control no-cache;
add_header Pragma no-cache;
}
# css/js文件
location ~ .*\.(js|css)?$ {
# 缓存有效期:7天
expires 7d;
access_log off;
}
# 图片资源
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf|flv|mp4|ico)$ {
expires 30d;
access_log off;
}
参数 | 说明 |
---|---|
Cache-Control: no-cache | 协商缓存,只能应用于http 1.1,会返回304(资源无更新) |
Cache-Control: no-store | 禁止缓存 |
Pragma: no-cache | 和 Cache-Control: no-cache 相同,应用于 http 1.0 和http 1.1 |
协商缓存的参数
- Last-Modified / IF-Modified-Since 验证修改时间
- Etag / IF-None-Match 验证文件指纹
参考
https://cli.vuejs.org/zh/guide/deployment.html
前端项目中 浏览器缓存的更新不及时问题及解决方法
中高级前端工程师都需要熟悉的技能–前端缓存
更多推荐
已为社区贡献34条内容
所有评论(0)