單頁應用部署時緩存策略


問題描述

前端網站采用Vue + Nginx的方式進行生產環境部署。

系統在發布更新次日,收到客戶的投訴,發現登錄系統之后,出現頁面空白問題,刷新幾次后顯示正常。查看日志發現:

2019/01/07 10:26:01 [error] 19#0: *833 open() "/.../static/js/0.4a66cb25e7f24262c3f6.js" failed (2: No such file or directory), client: XX.XX.XX.XX, server: localhost, request: "GET /static/js/0.4a66cb25e7f24262c3f6.js HTTP/1.1"

問題分析

由於vue在build之后,會重新生成index.html + static資源。從日志判斷,【/static/js/0.4a66cb25e7f24262c3f6.js】是上一版本的靜態資源。而index.html中get請求獲取,跟瀏覽器緩存有關

但是查看nginx配置,發現沒有配置緩存策略。


    server {
        listen       80 default_server;
        server_name  localhost;
        root         /www/;
        index        index.html index.htm;
        location / {
             try_files $uri $uri/  index.html;
        }
    }

當http頭中無緩存配置,那么將使用瀏覽器默認緩存策略,如下:

先放上結論吧,Chrome和Firefox對js、css之類的文件,在內存中的緩存時長,是: (訪問時間 - 該文件的最后修改時間) ÷ 10

  • 假設文件 a.js 最后編輯時間是 2018年12月1號 10點0分0秒;
  • Chrome的第一次訪問時間是 2018年12月1號 12點0分0秒;
  • 第一次訪問與文件編輯時間相差2小時,即7200秒,那么緩存時長就是720秒

解決方案

http請求頭中,通過cache-control聲明緩存策略。

  • 對於index.html采用no-cache策略,客戶端使用緩存,但是使用前需要與服務器確認版本狀態。
  • 對於static資源,采用客戶端緩存。

nginx配置參考:


  location /index.html {
    add_header "Cache-Control" "no-cache";
  }

  location /static/ {
    access_log none;
    expires 14d;
  }

  location / {
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://127.0.0.1:8081;
    client_max_body_size  500m;
  }

  location = / {
  }

參考資料

  1. https://blog.csdn.net/youbl/article/details/84879670
  2. https://www.cnblogs.com/feng9exe/p/8083237.html

原文鏈接:https://my.oschina.net/u/161336/blog/2999036


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM