没有设置cache-control,会发生什么?

1,103 阅读2分钟

http请求头里的cache-control是控制资源的缓存。对于强缓存和协商缓存,大家都很熟悉了。浏览器在请求资源的时候,会先判断是否使用强缓存,无强缓存则判断是否使用协商缓存,缓存都没有,再去服务器请求资源。

cache-control有好几个值,各自都有相应的缓存机制。详细可以去参考mdn上的http cache文档。

很多时候,服务器是不配置cache-control的。今天我就遇到了这个情况。代码已经很确定已经发送到服务器上了,但是在电脑上访问网站,获取到的资源,还是旧的资源。查找了很久,才找到具体原因。

对于没有设置cache-control的资源,浏览器有一个叫做10%的处理规则,来计算当前资源应该缓存的时间。

10%处理规则,就是(当前访问并进行缓存处理的时间-文件最后修改时间)/10,就是资源缓存时长。根据这个算法,在一些极端场景下,资源会有非常长的缓存时间。

例如:100天前发版,今天发现了bug,改完,并发布到了服务器上。用户很可能是昨天才第一次访问的网页,那么这个用户电脑上资源的缓存时长为10天。

If there is no Cache-Control header and no Expires header, but there is a Last-Modified header (which most web servers send by default for static assets), most browsers will use

heuristic freshness

to determine how long to cache that asset for.

The typical calculation for this (which is the one suggested by RFC 7234) is:

(current time - last modified time) / 10

So, for example, if the last modified time for an image states it was last changed 60 days ago, a browser might decide it could reasonably use the locally cached version of that image for 6 days before checking for a new version.

Note that in most cases, if you hit refresh, you are

telling

the browser to fetch a fresh version, so in that situation this logic wouldn't apply.

Freshness as determined by actual browsers:

针对这种场景,一劳永逸地解决方法是设置一个相对较短的强缓存时间。