利用Apache模块mod_expires和mod_headers实现文件缓存

转自:http://blog.youkuaiyun.com/fdipzone/article/details/7171863

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

LoadModule expires_module modules/mod_expires.so 去掉前面#

在.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文件中添加如下内容可以实现缓存:

2. 利用 mod_headers.

LoadModule headers_module modules/mod_headers.so 去掉前面#

<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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值