LAMP--Apache 配置静态缓存

2017-11-10

LAMP--Apache 配置静态缓存

这里的静态文件指的是图片、js、CSS 等文件,用户访问一个站点,其实大多数元素都是图片、js、CSS 等,这些静态文件其实是会被客户端的浏览器缓存到本地电脑上的,目的就是为了下次再请求时不再去服务器上下载,这样就加快了访问速度,提高了用户体验。但这些静态文件不能一直缓存,它总有一定的时效性,我们可以设置其过期时间。

本次配置使用 mod_expires.c 模块,使用 /usr/local/apache2/bin/apachectl -M 查看是否支持。不支持,得先安装,参照之前的“LAMP--apache 的扩展模块安装”。

在对应虚拟主机的配置文件中加入以下语句:

[root@localhost ~]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf
  <IfModule mod_expires.c>
  ExpiresActive on
  ExpiresByType p_w_picpath/gif "access plus 1 days"
  ExpiresByType p_w_picpath/jpeg "access plus 24 hours"
  ExpiresByType p_w_picpath/png "access plus 24 hours"
  ExpiresByType text/css "now plus 2 hours"
  ExpiresByType application/x-javascript "now plus 2 hours"
  ExpiresByType application/javascript "now plus 2 hours"
  ExpiresByType application/x-shockwave-flash "now plus 2 hours"
  ExpiresDefault "now plus 0 min"
  </IfModule>

重新加载配置文件

[root@localhost ~]# /usr/local/apache2/bin/apachectl -t
Syntax OK
[root@localhost ~]# /usr/local/apache2/bin/apachectl graceful

使用 curl 命令检测

[root@localhost ~]# curl -x127.0.0.1:80 'http://www.123.com/static/p_w_picpath/common/titlebg.png' -I
HTTP/1.1 200 OK
Date: Wed, 25 May 2016 02:11:38 GMT
Server: Apache/2.2.31 (Unix) PHP/5.6.10
Last-Modified: Wed, 25 May 2016 02:11:38 GMT
ETag: W/"802b7-13b-5341ab0597500"
Accept-Ranges: bytes
Content-Length: 315
Cache-Control: max-age=86400
Expires: Thu, 26 May 2016 02:11:38 GMT
Content-Type: p_w_picpath/png
[root@localhost ~]# curl -x127.0.0.1:80 'http://www.123.com/data/cache/style_1_forum_index.css?Vxf' -I
HTTP/1.1 200 OK
Date: Wed, 25 May 2016 02:07:43 GMT
Server: Apache/2.2.31 (Unix) PHP/5.6.10
Last-Modified: Wed, 25 May 2016 02:06:19 GMT
ETag: "80c82-e51-533a11e96e4ed"
Accept-Ranges: bytes
Content-Length: 3665
Cache-Control: max-age=7200
Expires: Wed, 25 May 2016 04:07:43 GMT
Content-Type: text/css

其中的缓存控制项 max-age 就是其生存时间。


另外 mod_headers.c 模块也能实现这个操作

同上:

<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 "\.(jpg|gif|jpeg|png|ico|flv|pdf)$">
header set cache-control "max-age=29030400"
</filesmatch>
</IfModule>

标题:LAMP--Apache 配置静态缓存
作者:散宜生
地址:https://17kblog.com/articles/2017/11/10/1510325488673.html