[英]How to prevent chrome load index.html from disk cache after 301 redirect
[英]How to prevent Chrome from using disk cache when the assets change?
我有一個由 Nginx 提供服務的 static 站點。我使用contenthash
來構建文件名中帶有 contenthash 的資產:
index.html
main.723f2b08bd448896ca78.js
main.18a850dffbe46cca9feb.css
當我編輯我的 JavaScript 代碼並重新部署站點時,根目錄更改為:
index.html
main.08ddcf9a702a6772ce2d.js # <- new hash
main.18a850dffbe46cca9feb.css
當我在 Chrome 中打開一個新選項卡時,輸入我的域名,然后按 Enter - 在“網絡”選項卡中,我看到 Chrome仍在加載舊文件:
Name Status Type Initiator Size Time
mydomain.com 200 document Other (disk cache) 4 ms
main.723f2b08bd448896ca78.js 200 script (index) (disk cache) 17 ms
main.18a850dffbe46cca9feb.css 200 stylesheet (index) (disk cache) 13 ms
當我單擊example.com
時,響應中的 HTML 包含舊腳本:
<script src="/main.723f2b08bd448896ca78.js"></script
此外, index.html
上的響應標頭已過時:
Content-Encoding: gzip
Content-Type: text/html
Date: Thu, 26 Jan 2023 09:21:31 GMT
ETag: W/"63d06108-202"
Last-Modified: Tue, 24 Jan 2023 22:51:52 GMT
X-DNS-Prefetch-Control: off
此外,當我單擊main.723f2b08bd448896ca78.js
時,響應標頭也已過時:
Accept-Ranges: bytes
Content-Length: 605458
Content-Type: application/javascript
Date: Thu, 26 Jan 2023 09:21:31 GMT
ETag: "63d06108-93d12"
Last-Modified: Tue, 24 Jan 2023 22:51:52 GMT
如果我重新加載頁面,Chrome 會正確加載新文件。 但是如果我再次打開一個新選項卡,輸入域,然后按 Enter - 它仍然會加載舊資產! 這給我留下了硬頁面重新加載( Ctrl + Shift + R
),最終重置了緩存。
當我在隱身模式下加載我的網站時,我得到了預期的正確文件:
Name Status Type Initiator Size Time
mydomain.com 200 document Other 557 B 634 ms
main.08ddcf9a702a6772ce2d.js 200 script (index) 606 kB 1.28 s
main.18a850dffbe46cca9feb.css 200 stylesheet (index) 87.2 kB 497 ms
index.html
響應:
<script src="/main.08ddcf9a702a6772ce2d.js"></script
index.html
響應頭:
Connection: keep-alive
Content-Encoding: gzip
Content-Type: text/html
Date: Thu, 26 Jan 2023 10:33:44 GMT
ETag: W/"63d249c7-202"
Last-Modified: Thu, 26 Jan 2023 09:37:11 GMT
Transfer-Encoding: chunked
main.08ddcf9a702a6772ce2d.js
響應頭:
Accept-Ranges: bytes
Connection: keep-alive
Content-Length: 605595
Content-Type: application/javascript
Date: Thu, 26 Jan 2023 10:33:44 GMT
ETag: "63d249c7-93d9b"
Last-Modified: Thu, 26 Jan 2023 09:37:11 GMT
我不明白我做錯了什么 - Nginx 正在返回Etag
和Last-Modified
新值。 contenthash
在部署之間發生變化。 然而 JS 文件仍然被非常積極地緩存。 這個問題發生在我和其他使用該網站的人身上。 在這種情況下,它導致了一個白屏死機,我不得不告訴大家做一個硬頁面重新加載(這對最終用戶來說是陌生和困惑的)。
有解決辦法嗎? 我不介意disk cache
,但如何告訴 Chrome 在資產文件更改時不要使用它? 這是 Nginx 配置錯誤嗎?
謝謝你。
告訴瀏覽器它可以緩存資源多長時間是你的工作。 您可以通過設置Cache-Control
響應 header ( MDN ) 來實現。 如果你不設置它,瀏覽器可以自行決定多長時間是合適的。 這似乎就是你的情況。
只需在index.html響應 header 上設置Cache-Control: no-cache
,這個問題就會 go 消失。 該頁面仍將由瀏覽器緩存,但瀏覽器不會使用它,除非先與服務器檢查它是否仍然是最新的(這就是ETag
的用途)。
但是,對於您的 static 資源,您應該設置較長的緩存時間,因為像這樣對文件名進行版本控制的全部目的是允許任何給定的文件名不可變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.