正确使用Expires标识处理,可以使得页面更加有效被缓冲,节约带宽资源。
apache配置:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType application/x-Javascript A604800
ExpiresByType text/css A604800
</IfModule>
或者
<ifmodule mod_expires.c>
<filesmatch "\.(jpg|gif|png|css|js)$">
ExpiresActive on
ExpiresDefault "access plus 600 minutes"
</filesmatch>
</ifmodule>
可以选用的时间参数有years months weeks days hours minutes seconds
也可以加在.htaccess文件:
#Expire Header
<FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf)$">
ExpiresDefault "access plus 2 hours"
</FilesMatch>
or
# Expire images header
ExpiresActive On
ExpiresDefault A0
ExpiresByType image/gif A2592000
ExpiresByType image/png A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/ico A2592000
ExpiresByType text/css A2592000
ExpiresByType text/javascript A2592000
#A2592000 means 1 month in the future (60*60*24*30=2592000)
nginx配置:
location ~* ^.+\.(jpg|jpeg|gif|png|swf|rar|zip|css|js|flv|mp3|wma|wmv|ram|rm)$ {
valid_referers none blocked *.veryi.com;
if ($invalid_referer) {
#rewrite ^/ ;
#return 412;
return 403;
}
access_log off;
root /opt/www;
expires 10h;
break;
}
或者
location ~ \.(gif|jpg|png|swf|flv|bmp)$ {
valid_referers none blocked *.veryi.com;
if ($invalid_referer) {
#rewrite ^/ ;
return 403;
}
expires 30d;
}
location ~ .*\.(js|css)?$
{
expires 3d;
}
测试:
curl -I
HTTP/1.1 200 OK
Server: Apache/2.0.63
Date: Tue, 21 Jun 2011 08:13:06 GMT
Content-Type: image/gif
Content-Length: 21734
Last-Modified: Tue, 21 Jun 2011 08:11:00 GMT
Connection: keep-alive
Expires: Thu, 21 Jul 2011 08:13:06 GMT
Cache-Control: max-age=2592000
Accept-Ranges: bytes
Etag和Expires的工作原理
在客户端通过浏览器发出第一次请求某一个URL时,根据 HTTP 协议的规定,浏览器会向服务器传送报头(Http Request Header),服务器端响应同时记录相关属性标记(Http Reponse Header),服务器端的返回状态会是200,格式类似如下:
HTTP/1.1 200 OK
Date: Tue, 03 Mar 2009 04:58:40 GMT
Content-Type: image/jpeg
Content-Length: 83185
Last-Modified: Tue, 24 Feb 2009 08:01:04 GMT
Cache-Control: max-age=2592000
Expires: Thu, 02 Apr 2009 05:14:08 GMT
Etag: “5d8c72a5edda8d6a:3239″