哪些 HTTP 状态代码是可缓存的?

Which HTTP status codes are cacheable?

如题所述,浏览器可以缓存哪些HTTP状态码?我快速搜索了一下,没有找到权威的答案。

本来我以为可能只有 200 OK 回复,但我找不到任何证据来支持这个想法。

根据 RFC7234 还允许缓存提供非 200(好的)代码的响应:

[...] The most common form of cache entry is a successful result of a retrieval request: i.e., a 200 (OK) response to a GET request, which contains a representation of the resource identified by the request target (Section 4.3.1 of [RFC7231]). However, it is also possible to cache permanent redirects, negative results (e.g., 404 (Not Found)), incomplete results (e.g., 206 (Partial Content)), and responses to methods other than GET if the method's definition allows such caching and defines something suitable for use as a cache key.

所以这取决于浏览器开发人员他想要缓存什么而不缓存什么。

简答

根据 RFC 7231, the current reference for content and semantics of the HTTP/1.1 protocol, the following HTTP status codes are defined as cacheable unless otherwise indicated by the method definition or explicit cache controls:

长答案

RFC 7231 声明了以下关于默认可缓存的 HTTP 状态代码:

6.1. Overview of Status Codes

[...] Responses with status codes that are defined as cacheable by default (e.g., 200, 203, 204, 206, 300, 301, 404, 405, 410, 414, and 501 in this specification) can be reused by a cache with heuristic expiration unless otherwise indicated by the method definition or explicit cache controls; all other status codes are not cacheable by default. [...]

一旦 HTTP 状态代码可扩展,接收者必须注意缓存具有无法识别的状态代码的响应:

6. Response Status Codes

The status-code element is a three-digit integer code giving the result of the attempt to understand and satisfy the request.

HTTP status codes are extensible. HTTP clients are not required to understand the meaning of all registered status codes, though such understanding is obviously desirable. However, a client MUST understand the class of any status code, as indicated by the first digit, and treat an unrecognized status code as being equivalent to the x00 status code of that class, with the exception that a recipient MUST NOT cache a response with an unrecognized status code. [...]

缓存还取决于 HTTP 方法:

4.2.3. Cacheable Methods

Request methods can be defined as "cacheable" to indicate that responses to them are allowed to be stored for future reuse. In general, safe methods that do not depend on a current or authoritative response are defined as cacheable; this specification defines GET, HEAD, and POST as cacheable, although the overwhelming majority of cache implementations only support GET and HEAD.

关于POST方法,有一个重要的细节:

4.3.3. POST

[...] Responses to POST requests are only cacheable when they include explicit freshness information [...]

有关详细信息,请查看 definition of each method

其他资源

  • RFC 7234:参考HTTP/1.1协议
  • 中的缓存
  • Check what browsers store in their cache