Cache-Control 会受本地时间影响么

Expires

  • 服务端和浏览器的时间可能不同, 导致缓存过期时间出现偏差
  • 客户端可以通过修改系统时间来继续使用缓存或提前使缓存失效

为了解决这个问题, HTTP/1.1 提出了 Cache-Control 响应头部字段

我的疑问是虽然 Cache-Control(max-age) 是相对时间,但是也是受本地实际影响吧

跟 Expires 感觉没什么区别 就是计算时间方式不一样 ……

阅读 4.2k
3 个回答

不会受影响,因为过期的时间是根据浏览器收到的响应报文中的(Date+max-age)计算的。这两个值都是由服务器或cdn传递过来的,不依赖于客户端。

不,cache-control是相对时间,而expires是绝对时间,而且用的是服务器时间,如果服务器时间和客户端时间不同步就会缓存失效。
而cache-control的典型范例是max-age=<seconds>,代表本地客户端获取到资源之后在客户端缓存多少秒,所以和服务器时间是否同步无关。

我之前有篇文章提到了这个,你可以参考: https://blog.dteam.top/posts/...

补充一下,其它两人写的应该都有问题
先说一下,关于题主这个“Cache-Control(max-age) 会受本地时间影响么”
我查的结果是会,所以我也不理解有些文章说的“服务端和浏览器的时间可能不同, 导致缓存过期时间出现偏差” “但有一个问题是到期时间是由服务端生成的,如果客户端时间跟服务器时间不一致,这就会导致缓存命中的误差。”

Cache-Control:max-age=

max(本地电脑时间 - 上次响应的Date字段, 上次响应的Age字段)
做比较


我用英文搜了搜,也没搜到关于“服务端和浏览器的时间可能不同, 导致缓存过期时间出现偏差”的什么靠谱的解释
又搜了搜,从RFC2616里翻出来一段
The max-age directive takes priority over Expires, so if max-age is present in a response, the calculation is simply:

  freshness_lifetime = max_age_value

Otherwise, if Expires is present in the response, the calculation is:

  freshness_lifetime = expires_value - date_value

Note that neither of these calculations is vulnerable to clock skew,since all of the information comes from the origin server.

又一段
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(所以max_age也是需要同步的,不同步会有问题). 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.


不过expires改成max-age有另外一个好处,就是expires需要时常改它的值,而max-age不需要经常改(当然,你也可以写段代码自动改expires的值)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题