--- title: Cache-Control slug: Web/HTTP/Headers/Cache-Control tags: - Cache-Control - HTTP - 请求头 translation_of: Web/HTTP/Headers/Cache-Control ---
Cache-Control 通用消息头字段,被用于在http请求和响应中,通过指定指令来实现缓存机制。缓存指令是单向的,这意味着在请求中设置的指令,不一定被包含在响应中。
| Header type | {{Glossary("General header")}} |
|---|---|
| {{Glossary("Forbidden header name")}} | no |
| {{Glossary("Simple response header", "CORS-safelisted response-header")}} | yes |
指令格式具有以下有效规则:
客户端可以在HTTP请求中使用的标准 Cache-Control 指令。
Cache-Control: max-age=<seconds> Cache-Control: max-stale[=<seconds>] Cache-Control: min-fresh=<seconds> Cache-control: no-cache Cache-control: no-store Cache-control: no-transform Cache-control: only-if-cached
服务器可以在响应中使用的标准 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=<seconds> Cache-control: s-maxage=<seconds>
Cache-Control指令拓展缓存指令不是核心HTTP缓存标准文档的一部分,使用前请注意检查兼容性!
Cache-control: immutable Cache-control: stale-while-revalidate=<seconds> Cache-control: stale-if-error=<seconds>
publicmax-age指令或Expires消息头;2. 该响应对应的请求方法是 POST 。)privateno-cacheno-storemax-age=<seconds>Expires相反,时间是相对于请求的时间。s-maxage=<seconds>max-age或者Expires头,但是仅适用于共享缓存(比如各个代理),私有缓存会忽略它。max-stale[=<seconds>]min-fresh=<seconds>stale-while-revalidate=<seconds> {{experimental_inline}}stale-if-error=<seconds> {{experimental_inline}}must-revalidatemax-age),在成功向原始服务器验证之前,缓存不能用该资源响应后续请求。proxy-revalidateimmutable {{experimental_inline}}If-None-Match或If-Modified-Since)来检查更新,即使用户显式地刷新页面。在Firefox中,immutable只能被用在 https:// transactions. 有关更多信息,请参阅这里。no-transformContent-Encoding、Content-Range、Content-Type等HTTP头不能由代理修改。例如,非透明代理或者如Google's Light Mode可能对图像格式进行转换,以便节省缓存空间或者减少缓慢链路上的流量。no-transform指令不允许这样做。only-if-cached发送如下响应头可以关闭缓存。此外,可以参考Expires和Pragma消息头。
Cache-Control: no-store
对于应用程序中不会改变的文件,你通常可以在发送响应头前添加积极缓存。这包括例如由应用程序提供的静态文件,例如图像,CSS文件和JavaScript文件。另请参阅Expires标题。
Cache-Control:public, max-age=31536000
指定 no-cache 或 max-age=0, must-revalidate 表示客户端可以缓存资源,每次使用缓存资源前都必须重新验证其有效性。这意味着每次都会发起 HTTP 请求,但当缓存内容仍有效时可以跳过 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