利用Apache模块mod_expires和mod_headers...

利用Apache模块mod_expires和mod_headers实现文件缓存,Add an Expires header|为文件头指定Expires
大家在使用YSlow的网站速度优化,常会看到Add an Expires header这一条分值很低,搜索很多但还不知道怎么该。下面就是答案。
Add an Expires header / 为文件头指定Expires
给静态文件加上过期标志。让浏览器或者CDN服务器缓存起来,加速图片和其他静态文件的加载。
Expires是浏览器Cache机制的一部分,浏览器的缓存取决于Header中的四个值: Cache-Control, Expires, Last-Modified, ETag。
优化这个选项,所要做的是对站内所有的文件有针对性的设置Cache-Control和Expires.
我们要实现加上过期标志可以利用apache模块mod_expires和mod_headers。
通过配置.htaccess文件, 可以轻易地按文件类别设置缓存时间。对提高网站速度有一定帮助。
1. 利用mod_expires
在.htaccess中添加如下语句:
<ifmodule mod_expires.c>
expiresactive _disibledevent=>
</filesmatch>
# css, js, swf类的文件缓存一个星期
<filesmatch “\.(css|js|swf)$”>
header set cache-control “max-age=604800″
</filesmatch>
# jpg,gif,jpeg,png,ico,flv,pdf等文件缓存一年
<filesmatch “\.(ico|gif|jpg|jpeg|png|flv|pdf)$”>
header set cache-control “max-age=29030400″
</filesmatch>
</ifmodule>
以下为样本代码:
<FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$”>
Header set Cache-Control “max-age=604800, public”
</FilesMatch>
<FilesMatch “\.(xml|txt)$”>
Header set Cache-Control “max-age=18000, public, must-revalidate”
</FilesMatch>
<FilesMatch “\.(html|htm|php)$”>
Header set Cache-Control “max-age=3600, must-revalidate”
</FilesMatch>
如果不行,直接在httpd.conf末端添加:
<IfModule mod_expires.c>
ExpiresActive on
ExpiresDefault "access plus 12 month"
ExpiresByType text/html "access plus 12 months"
ExpiresByType text/css "access plus 1 months"
ExpiresByType image/gif "access plus 12 months"
ExpiresByType image/ico "access plus 12 months"
ExpiresByType image/jpeg "access plus 12 months"
ExpiresByType image/jpg "access plus 12 months"
ExpiresByType image/png "access plus 12 months"
EXpiresByType application/x-shockwave-flash "access plus 12 months"
EXpiresByType application/x-javascript "access plus 12 months"
ExpiresByType video/x-flv "access plus 12 months"
</IfModule>&#65279;
Tags: 

延伸阅读

最新评论

发表评论