http缓存

如何让一个资源可缓存

HTTP 1.1 风格的Cache-Control 响应头中的 max-age指令
HTTP 1.0 风格的 Expires 响应头
Last-Modified响应头

缓存的组成

freshness + validation

freshness 缓存有效期

The freshness lifetime is calculated based on several headers. If a "Cache-control: max-age=N" header is specified, then the freshness lifetime is equal to N. If this header is not present, which is very often the case, it is checked if an Expires header is present. If an Expires header exists, then its value minus the value of the Date header determines the freshness lifetime. Finally, if neither header is present, look for a Last-Modified header. If this header is present, then the cache's freshness lifetime is equal to the value of the Date header minus the value of the Last-modified header divided by 10.
缓存有效期是根据多个header信息来计算得出,如果含有"Cache-control: max-age=N"则有效期等于N,如果不存在,多数情况下是不存在~~。
检查是否存在Expires,如果存在则有效期等于Expires值减去Date的值。如果两者都不存在,则检查Last-Modified是否存在,然后利用Date减去其值再除以10即:(Date-(Last-modified))/10

  • 如何更新缓存时间设置的很长的文件

    修改文件名称
    e.g
    原始文件 gift.png 有效期1年
    中途更新 gift.1.1.png vs gift.png?v=1.1
    多数情况下两者效果是一致的,但是通过请求参数的方式会在Squid等一些代 理中缓存命中失败,
    Revving Filenames: don’t use querystring,但这篇文章是 2008年的,有时间再验证一下

缓存失效时间

The expiration time is computed as follows:

expirationTime = responseTime + freshnessLifetime - currentAge

validation缓存校验

缓存过期后,请求会通过cache server向origin server 访问请求资源

  • 强校验
    Etag + If-None-Match:服务端将资源生成Etag值,并通过response header发送给客户端。当客户端进行缓存校验时将该值通过If-None-Match携带至服务端,若该资源的Etag值不匹配则返回200并返回新的资源,如果匹配上了则返回304表示未修改,并返回空的响应体
  • 弱校验
    Last-modified + Since-last-modified: response携带 Last-modified至客户端,校验时再由 Since-last-modified将值携带至服务端,如果不匹配则返回200与新资源,如果匹配则返回304.

vary

Vary头域值指定了一些请求头域,这些请求头域用来决定: 当缓存中存在一个响应,并且该缓存没有过期失效,是否被允许去利用此响应去回复后续请求而不需要重验证(revalidation)。
第一次请求时获取相应,在缓存了该响应的同时会缓存vary中存在的头部信息例如user-agent
第二次请求时,校验该请求中user-agent是否与第一次的相同,如果相同则可以直接使用缓存,否则需要从orifgin获取

参考

MDN Cache
Cache tutorial
Cache-contral : must-revalidate

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容