vue項目強制清除頁面緩存


異常描述:

支付寶中內嵌h5項目(vue框架開發),前端重新打包上傳之后訪問頁面會導致頁面空白、頁面tab點擊異常之類異常情況,需要手動清除支付寶緩存才可以正常訪問。

解決方案:

在HTTP協議中,只有后端返回 expires 或 Cache-Control:max-age=XXX, 前端才緩存。
但在瀏覽器中,默認會對 html css js 等靜態文件、以及重定向進行緩存,如果在HEAD頭中指定:

<HEAD>
<METAHTTP-EQUIV="Pragma"CONTENT="no-cache">
<METAHTTP-EQUIV="Cache-Control"CONTENT="no-cache">
<METAHTTP-EQUIV="Expires"CONTENT="0">
</HEAD>

瀏覽器不會緩存html,但是還是會對重定向緩存,並且這種方式並不規范,可能有的瀏覽器不支持。
我的最終解決方案是:
1) 對hash過的靜態文件還是采用默認方式,客戶端會緩存。
2)對html文件,返回時增加頭:Cache-Control,必須每次來服務端校驗,根據etag返回200或者304
對應的nginx配置如下:

 1 upstream example-be {
 2   ip_hash;
 3   server unix:/run/example-be.sock;
 4 }
 5 server{
 6   listen 80; #監聽端口
 7   server_name example.com
 8 
 9   # 后台api
10   location ~ ^/api {
11     proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
12     include uwsgi_params;
13     uwsgi_pass example-be;
14   }
15 
16   # 前端靜態文件
17   location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
18     root /var/www/example-fe/dist/;
19   }
20 
21   # 前端html文件
22   location / {
23     # disable cache html
24     add_header Cache-Control 'no-cache, must-revalidate, proxy-revalidate, max-age=0';
25 
26     root /var/www/example-fe/dist/;
27     index index.html index.htm;
28     try_files $uri /index.html;
29   }
30 }

由於瀏覽器緩存靜態文件的時間不可控,我們可以在nginx上自己配置expires 1M(1個月)
# 前端靜態文件

1 location ~* \.(gif|jpg|jpeg|png|css|js|ico|eot|otf|fon|font|ttf|ttc|woff|woff2)$ {
2   root /var/www/example-fe/dist/;
3   expires 1M;
4   add_header Cache-Control "public";
5 }

 


免責聲明!

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



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