本文主要内容为我对前端缓存的一些见解,和一些服务器配置的运用。相信你们都有了解过雅虎的35条前端优化法则吧,前端缓存也是前端优化当中的必不可少的一部分,雅虎推荐为"Add an Expires or a Cache-Control Header",但是对这2个http header 咱们又知道多少呢。前端
HTTP 1.0 的header,nginx对expires有如下的一些配置:nginx
expires 24h;
expires modified +24h;
expires @24h;
expires 0;
expires -1;
#Thu, 01 Jan 1970 00:00:01 GMT
expires epoch;
expires $expires;
add_header Cache-Control private;复制代码
当咱们对服务器资源设置expires时,就会告诉浏览器(或代理)这个资源咱们要多久到期,以下图的响应头
浏览器
HTTP1.1 定义的规则
与expires相似,其对应关系为缓存
expires --- cache-control
last-modified --- etag
if-modified-since --- if-match复制代码
功能相似,取值稍有不一样服务器
Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>] //代表客户端愿意接收一个已通过期的资源。 可选的设置一个时间(单位秒),表示响应不能超过的过期时间。
Cache-Control: min-fresh=<seconds> //表示客户端但愿在指定的时间内获取最新的响应。
Cache-control: no-cache
Cache-control: no-store
Cache-control: no-transform
Cache-control: only-if-cached //代表若是缓存存在,只使用缓存,不管原始服务器数据是否有更新。复制代码
Cache-control: must-revalidate //缓存必须在使用以前验证旧资源的状态,而且不可以使用过时资源。
Cache-control: no-cache //强制全部缓存了该响应的缓存用户,在使用已存储的缓存数据前,发送带验证器的请求到原始服务器
Cache-control: no-store
Cache-control: no-transform
Cache-control: public //代表响应能够被任何对象(包括:发送请求的客户端,代理服务器,等等)缓存。
Cache-control: private //代表响应只能被单个用户缓存,不能做为共享缓存(即代理服务器不能缓存它)。
Cache-control: proxy-revalidate
Cache-Control: max-age=<seconds> //设置缓存存储的最大周期,超过这个时间缓存被认为过时(单位秒)。
Cache-control: s-maxage=<seconds> //覆盖max-age 或者 Expires 头,可是仅适用于共享缓存(好比各个代理),而且私有缓存中它被忽略。复制代码
相同点:
客户端每次请求都会与服务器创建链接
不一样点:
no-cache,客户端会缓存资源,再次请求时会与对原始服务器上的资源进行验证,未更改->304,已更改->200;
no-store,客户端不会缓存资源,每次请求都从新下载原始服务器资源,对应响应状态码 200前端优化