http协议无状态,所以缓存设定从两方面考虑.客户端浏览器和服务器端.

浏览器端实现过期机制. 服务器端实现验证机制.

缓存机制.

为了减轻服务器负担,也减少网络传输数量.http1.0定义了Expires. http1.1 进一步定义了cache-control字段.

Expires: 返回一个date 类型时间戳,指定该文件被浏览器缓存到什么时间后过期.这个字段貌似在F5刷新时候仍会重新发送http请求.

Cache-Control:该字段定义了很多子项,  本人只关心浏览器端返回字段,如max-age 秒为单位,覆盖expires字段.no-cache 不缓存,public 可共享,private如仅限于某个用户,no-store不应被存储,no-transform 不应转换存储形式,must-revalidate必须向服务器验证.

 

适用http版本的不同,决定了在使用cache-control的同时必须使用expires,否则无法向下兼容.

cache-control的优先级高于expires

配置: nginx  nginx 的http_headers modules 支持expires 声场cache-control 和expires 字段. ngx_headers_more是增强版http头设置工具,支持自定义headers . 用法为more_set_headers "xx:xxx"  (

ngx_headers_more 包下载地址:http://github.com/agentzh/headers-more-nginx-module包含该模块

重新编译nginx 源码并 --add-module=/path/to/headers-more-nginx-module

)

//对图片,flash文件在浏览器本地缓存30天
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$
{
expires 30d;
}
//对js,css文件在浏览器本地缓存1小时
location ~ .*\.(js|css)$
{
expires 1h;
}

apache 要设置LoadModule expires_module modules/mod_expires.so ;或者LoadModule headers_module modules/mod_headers.so

验证机制.

主要是last-modified 和Etag

浏览器请求服务器端,服务器端返回包含last-modified字段,客户端再次请求带上if-modified-since:字段,服务器验证该字段和last-modified字段相同则返回304,不同则返回200.304 之后浏览器从本地加载.

Etag 类似. 浏览器请求,服务器返回包含etag,客户端再次请求带上if-none-match,服务器验证etag和if-none-match相同则返回304,不同则返回200

 

posted on 2016-06-19 23:22  任城三爷  阅读(244)  评论(0编辑  收藏  举报