--- title: Cache-Control slug: Web/HTTP/Headers/Cache-Control tags: - Cache-Control - General Header - HTTP - HTTP Header - Reference ---
Cache-Control
標頭中的指令用來控制 HTTP 請求、回應的快取行為。HTTP 請求跟回應可以擁有不同的快取控制指令。
Header type | {{Glossary("General header")}} |
---|---|
{{Glossary("Forbidden header name")}} | no |
{{Glossary("CORS-safelisted response header")}} | yes |
快取指令必須遵守這些規則:
可以在 HTTP 請求中使用的標準 Cache-Control
指令
Cache-Control: max-age=<秒數> Cache-Control: max-stale[=<秒數>] Cache-Control: min-fresh=<秒數> Cache-Control: no-cache Cache-Control: no-store Cache-Control: no-transform Cache-Control: only-if-cached
可以在 HTTP 回應中使用的標準 Cache-Control
指令
Cache-Control: must-revalidate Cache-Control: no-cache Cache-Control: no-store Cache-Control: no-transform Cache-Control: public Cache-Control: private Cache-Control: proxy-revalidate Cache-Control: max-age=<秒數> Cache-Control: s-maxage=<秒數>
這些擴充的 Cache-Control
指令不是 HTTP 快取的核心標準。使用前請檢查相容性,客戶端會直接忽略不支援的指令。
Cache-Control: immutable Cache-Control: stale-while-revalidate=<秒數> Cache-Control: stale-if-error=<秒數>
這些指令定義 HTTP 請求/回應是否可以做快取、儲存在哪,以及使用前是否要跟後端伺服器做驗證
public
private
no-store
。這個指令不是用來防止快取軟體儲存回應的。no-cache
no-cache
跟 immutable
一起使用。如果你真的不要任何快取軟體儲存你的回應,可以使用 no-store
。這個指令不是用來防止快取軟體儲存回應的。no-store
max-age=0
來清除快取,並強制向後端伺服器做驗證。(其他指令跟 no-store
一起使用都無效)max-age=<秒數>
Expires
不一樣,這個指令是相對於請求當下的時間。s-maxage=<秒數>
max-age
或者 Expires
標頭,不過只對共用快取軟體生效(比如 nginx)。私有快取會無視這個指令。max-stale[=<秒數>]
min-fresh=<秒數>
stale-while-revalidate=<秒數>
{{Experimental_Inline}}max-age
的值。想了解更多細節請到 "Keeping things fresh with stale-while-revalidate
" 。stale-if-error=<秒數>
{{Experimental_Inline}}must-revalidate
proxy-revalidate
must-revalidate
類似,不過只對共用快取軟體生效(比如 nginx)。私有快取會無視這個指令。immutable
If-None-Match
或 If-Modified-Since
)。 Clients that aren't aware of this extension must ignore them as per the HTTP specification. 在 Firefox 中, immutable
只有在使用 https://
時會生效。想知道更多資訊,可以閱讀這篇文章。no-transform
only-if-cached
If-None-Match
是沒有意義的。由伺服器在 HTTP 回應中設定 only-if-cached
指令也沒有意義。想要禁止快取一個資源,你可以在回應中設定這個標頭:
Cache-Control: no-store
這個 no-store
指令使得回應再也不會被儲存,但它無法防止使用先前儲存、而且仍有效的快取。多設定 max-age=0
可以強制執行驗證(也就會清除既有快取)。
Cache-Control: no-store, max-age=0
Cache-Control: private,no-cache,no-store,max-age=0,must-revalidate,pre-check=0,post-check=0
對於那些不會更新的檔案,你可以在回應中使用下列這個激進的標頭。比如說用在圖片、CSS 檔案,以及 JavaScript 檔案。附帶一提,也可以看看 Expires
標頭。
Cache-Control: public, max-age=604800, immutable
no-cache
、max-age=0, must-revalidate
是同樣的意思。
表示客戶端可以儲存資源,但使用它前必須做驗證。這表示每次都會發生 HTTP 請求,不過只要沒過期就不用下載完整內容
Cache-Control: no-cache
Cache-Control: max-age=0, must-revalidate
附帶一提: 這個設定可以在伺服器掛掉的時候使用過期資源
Cache-Control: max-age=0
Specification | Status | Comment |
---|---|---|
{{RFC(8246, "HTTP Immutable Responses")}} | IETF RFC | |
{{RFC(7234, "Hypertext Transfer Protocol (HTTP/1.1): Caching")}} | IETF RFC | |
{{RFC(5861, "HTTP Cache-Control Extensions for Stale Content")}} | IETF RFC | Initial definition |
{{Compat("http.headers.Cache-Control")}}
Cache-Control
for civilians