岚岚天空

Vue项目打包部署Nginx配置及前端缓存问题解决

彭世瑜 830 0

1、部署单个站点

server {
    listen       80;
    server_name  localhost;


    location / {
      root   /app;    
      index  index.html;
      try_files $uri $uri/ /index.html;
    }
}


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、缓存问题解决

浏览器缓存分类:

1、强制缓存

  • Expires:依赖本地时间和服务器时间

  • Cache-control:max-age=10

2、协商缓存

  • last-modified:文件修改时间

  • ETag:文件指纹

3、禁用缓存

  • 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 验证文件指纹


本文标签: 缓存 部署 Nginx vue

发表评论 (830人参与, 0 条评论)

评论列表

    快来评论,快来抢沙发吧~