友声网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
开启左侧

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

[复制链接]
admin 发表于 2017-12-22 09:59 | 显示全部楼层 |阅读模式
利用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中添加如下语句:
  1. <ifmodule mod_expires.c>
  2. expiresactive on

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

  5. #html,plain-text缓存300秒
  6. expiresbytype text/html a300
  7. expiresbytype text/plain a300

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

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

  13. #image类缓存一个星期
  14. expiresbytype image/jpeg a604800
  15. expiresbytype image/gif a604800
  16. expiresbytype image/png a604800

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

  21. </ifmodule>
复制代码

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

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

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

  4. header set cache-control “max-age=3600″
  5. </filesmatch>

  6. # css, js, swf类的文件缓存一个星期
  7. <filesmatch “\.(css|js|swf)$”>
  8. header set cache-control “max-age=604800″
  9. </filesmatch>
  10. # jpg,gif,jpeg,png,ico,flv,pdf等文件缓存一年
  11. <filesmatch “\.(ico|gif|jpg|jpeg|png|flv|pdf)$”>
  12. header set cache-control “max-age=29030400″
  13. </filesmatch>

  14. </ifmodule>
复制代码

以下为样本代码:
  1. <FilesMatch “\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$”>
  2. Header set Cache-Control “max-age=604800, public”
  3. </FilesMatch>
  4. <FilesMatch “\.(xml|txt)$”>
  5. Header set Cache-Control “max-age=18000, public, must-revalidate”
  6. </FilesMatch>
  7. <FilesMatch “\.(html|htm|php)$”>
  8. Header set Cache-Control “max-age=3600, must-revalidate”
  9. </FilesMatch>
复制代码

RSS|无图版|手机版|友声网 ( 鲁ICP备15020090号-1 )|网站地图 | 点击这里给我发消息 |

GMT+8, 2024-4-25 14:47 , Processed in 0.014674 second(s), 7 queries , MemCache On.

Powered by Discuz! X

© ys166.com

快速回复 返回顶部 返回列表