ETag and HTTP caching | Redowan’s Reflections
当响应可重用时,源服务器不需要处理请求 - 因此它不需要解析和路由请求、基于 cookie 恢复会话、查询数据库以获取结果或渲染模板引擎。这减少了服务器的负载。
在 HTTP 缓存规范中,缓存主要有两种类型:私有缓存和共享缓存。
私有缓存
私有缓存是与特定客户端绑定的缓存——通常是浏览器缓存。由于存储的响应不与其他客户端共享,因此私有缓存可以为该用户存储个性化响应。
Cache-Control: private
HTTP/1.1 200 OK
Cache-Control: private
共享缓存
启发式缓存
HTTP 被设计为尽可能多地缓存,因此即使没有给出
Cache-Control
,如果满足某些条件,响应也会被存储和重用。这称为启发式缓存。
Last-Modified
HTTP/1.1 200 OK
Last-Modified: Tue, 22 Feb 2021 22:22:22 GMT
据启发,全年未更新的内容将在之后的一段时间内不会更新。因此,客户端存储此响应(尽管缺少
max-age
)并重用它一段时间。重复使用多长时间取决于实施情况,但规范建议存储后的时间约为 10%(本例中为 0.1 年)
启发式缓存是在
Cache-Control
支持被广泛采用之前出现的一种解决方法,基本上所有响应都应显式指定Cache-Control
标头。
缓存的状态
确定响应何时新鲜、何时陈旧的标准是
age
。在 HTTP 中,age
是自生成响应以来经过的时间。这与其他缓存机制中的 TTL 类似。
Age
和 Cache-Control: max-age
HTTP/1.1 200 OK
Cache-Control: max-age=604800
Age: 86400
接收该响应的客户端将发现它在剩余的 518400 秒内保持新鲜
Expries
在 HTTP/1.0 中,新鲜度过去由
Expires
标头指定。
HTTP/1.0 200 OK
Expires: Tue, 28 Feb 2022 22:22:22 GMT
Expires
标头使用显式时间而不是指定经过的时间来指定缓存的生命周期。
时间格式难以解析,发现了许多实现错误,并且有可能通过故意移动系统时钟来引发问题;因此,
max-age
(用于指定经过的时间)在 HTTP/1.1 中被采用为Cache-Control
Vary
no-cache
和 no-store
no-cache
However, that usage of
max-age=0
is a remnant of the fact that many implementations prior to HTTP/1.1 were unable to handle theno-cache
directive — and so to deal with that limitation,max-age=0
was used as a workaround.
然而,max-age=0
的使用是 HTTP/1.1 之前的许多实现无法处理no-cache
指令这一事实的残余 - 因此为了处理该限制,max-age=0
被用作解决方法。
The
no-cache
directive does not prevent the storing of responses but instead prevents the reuse of responses without revalidation.
no-cache
指令不会阻止存储响应,而是阻止在不重新验证的情况下重复使用响应。
no-store
If you don’t want a response stored in any cache, use
no-store
.
如果您不希望将响应存储在任何缓存中,请使用no-store
。
You may think adding
no-store
would be the right way to opt-out of caching.
您可能认为添加no-store
是选择退出缓存的正确方法。
However, it’s not recommended to grant
no-store
liberally, because you lose many advantages that HTTP and browsers have, including the browser’s back/forward cache.
但是,不建议随意授予no-store
,因为你会失去 HTTP 和浏览器所具有的许多优势,包括浏览器的后退/前进缓存。
Therefore, to get the advantages of the full feature set of the web platform, prefer the use of
no-cache
in combination withprivate
.
因此,要获得 Web 平台完整功能集的优势,最好将no-cache
与private
结合使用