Poison

Cache-Control: max-age

一直以为 max-age 设置的值表示本地浏览器接收到响应后从当前时刻开始计算的可存活的时间,今天查了个问题,发现并不是。根据 RFC 中的描述,max-age 表示自源站服务器端生成响应后的最大生存时间,并不是自本地浏览器接收到响应后的最大生存时间。

A response’s age can be calculated in two entirely independent ways:

  1. now minus date_value, if the local clock is reasonably well synchronized to the origin server’s clock. If the result is negative, the result is replaced by zero.
  2. age_value, if all of the caches along the response path implement HTTP/1.1.

Given that we have two independent ways to compute the age of a response when it is received, we can combine these as corrected_received_age = max(now - date_value, age_value) and as long as we have either nearly synchronized clocks or all HTTP/1.1 paths, one gets a reliable (conservative) result.

同时发现对没有设置 Cache-Control 的资源,浏览器对部分资源进行了 If-Modified-Since 探测,而部分资源没有进行探测直接使用了本地缓存,查了下文档,原来是根据资源的 Last-Modified 距当前时间的差值来决定是否缓存一段时间,简单来说就是如果一个资源上次修改的时间已经很久了,那么我们可以认为在一定时间段内,该资源不会被修改,所以这时即使没有设置 Cache-Control,浏览器也会将该资源缓存一段时间。典型的缓存时间计算公式为 (current time - last modified time) / 10

Reference

RFC 2616 - Hypertext Transfer Protocol – HTTP/1.1 - 13.2.3 Age Calculations
RFC 7234 - Hypertext Transfer Protocol (HTTP/1.1): Caching - 4.2.2. Calculating Heuristic Freshness
http - What happens if you don’t set cache-control header? - Webmasters Stack Exchange