admin 发表于 2017-12-22 09:59

利用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 on

#默认所有文件缓存时间设置为300秒
expiresdefault a300

#html,plain-text缓存300秒
expiresbytype text/html a300
expiresbytype text/plain a300

#css, javascript缓存一个小时
expiresbytype text/css a3600
expiresbytype application/x-javascript a3600

#图标文件缓存30天
expiresbytype image/x-icon a2592000

#image类缓存一个星期
expiresbytype image/jpeg a604800
expiresbytype image/gif a604800
expiresbytype image/png a604800

#其它文件缓存一个星期
expiresbytype application/x-shockwave-flash a604800
expiresbytype video/x-flv a604800
expiresbytype application/pdf a604800

</ifmodule>
但有一个问题是我们常用的Apache主机经常不怎么支持mod_expires,没有关系,我们用另一个模块使用mod_headers。

同样在.htaccess文件中添加如下内容可以实现缓存:
<ifmodule mod_headers.c>

# htm,html,txt类的文件缓存一个小时
<filesmatch “\.(html|htm|txt)$”>

header set cache-control “max-age=3600″
</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>
页: [1]
查看完整版本: 利用Apache模块mod_expires和mod_headers实现文件缓存