一個(gè)最簡(jiǎn)單的支持大部分主流瀏覽器的 headers 集如下:
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
-
Cache-Control作用于HTTP1.1
HTTP1.1中啟用Cache-Control 來(lái)控制頁(yè)面的緩存與否,這里介紹幾個(gè)常用的參數(shù):
no-cache,瀏覽器和緩存服務(wù)器都不應(yīng)該緩存頁(yè)面信息;public,瀏覽器和緩存服務(wù)器都可以緩存頁(yè)面信息;no-store,請(qǐng)求和響應(yīng)的信息都不應(yīng)該被存儲(chǔ)在對(duì)方的磁盤(pán)系統(tǒng)中;must-revalidate,對(duì)于客戶機(jī)的每次請(qǐng)求,代理服務(wù)器必須想服務(wù)器驗(yàn)證緩存是否過(guò)時(shí)
-
Pragma作用于HTTP 1.0
HTTP1.0中通過(guò)Pragma控制頁(yè)面緩存,通常設(shè)置的值為no- cache,不過(guò)這個(gè)值不這么保險(xiǎn),通常還加上Expires置為0來(lái)達(dá)到目的。但是如我們刻意需要瀏覽器或緩存服務(wù)器緩存住我們的頁(yè)面這個(gè)值則要設(shè)置為Pragma。
-
Expires作用于proxies
表示存在時(shí)間,允許客戶端在這個(gè)時(shí)間之前不去檢查(發(fā)請(qǐng)求),等同
max-age的 效果。但是如果同時(shí)存在,則被Cache-Control的max-age覆蓋。 格式:Expires:時(shí)間,后面跟一個(gè)時(shí)間或者日期,超過(guò)這個(gè)時(shí)間后緩存失效。也就是瀏覽器發(fā)出請(qǐng)求之前,會(huì)檢查這個(gè)時(shí)間是否失效,若失效,則瀏覽器會(huì)重新發(fā)出請(qǐng)求。
HTML
通過(guò)添加 <meta> 標(biāo)簽來(lái)禁止瀏覽器緩存(代碼必須包含在 <head> 標(biāo)簽中)
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
其他環(huán)境的設(shè)置
- .htaccess (Apache)
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
- Java Servlet
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
- PHP
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
- ASP
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate"
Response.addHeader "Pragma", "no-cache"
Response.addHeader "Expires", "0"
- ASP.NET
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");
- Ruby on Rails
response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'
response.headers['Pragma'] = 'no-cache'
response.headers['Expires'] = '0'
- Python on Flask
resp.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
resp.headers["Pragma"] = "no-cache"
resp.headers["Expires"] = "0"
- Google Go
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
responseWriter.Header().Set("Pragma", "no-cache")
responseWriter.Header().Set("Expires", "0")
Resources
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
后記
上述方案對(duì)于 Safari 并無(wú)鳥(niǎo)用,一種比較正規(guī)的方案是:
$(window).bind("pageshow", function (event) {
if (event.originalEvent.persisted) {
window.location.reload();
}
});