您的位置:首页 > 运维架构 > Apache

LAMP--Apache 配置静态缓存

2016-07-05 09:32 579 查看
这里的静态文件指的是图片、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 image/gif "access plus 1 days"
ExpiresByType image/jpeg "access plus 24 hours"
ExpiresByType image/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/image/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: image/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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  apache 静态缓存