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 anExpires
header is present. If anExpires
header exists, then its value minus the value of theDate
header determines the freshness lifetime. Finally, if neither header is present, look for aLast-Modified
header. If this header is present, then the cache's freshness lifetime is equal to the value of theDate
header minus the value of theLast-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
vsgift.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
获取