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

apache配置静态文件缓存

2015-07-31 23:06 686 查看
设置静态内容缓存,就是让网页里的图片还有js、css这些资源、包括页面缓存到本地而不是每次都去服务器请求资源,而是设置规定的时间,这样做可以减轻服务器的带宽压力和使网页打开速度加快,这样以来用户体验就会好一些。
那么如何来设置缓存时间呢?

先确认apache是否加载mod_expires
# /usr/local/apache2/bin/apachectl -M|grep -i expires
expires_module (shared) //如没有任何显示,说明需要先编译expires模块

编译一个mod_expires.c 参考以下:
编译:apxs2 -c mod_expires.c安装:apxs2 -i mod_expires.la或,一句话命令:§ apxs2 -iac mod_expires.c执行完成后,expires模块被安装到:/usr/lib/apache2/modules,这里可能会报告权限错误,请确保有管理员权限方可执行安装模块动作。在apache虚拟主机加入以下代码:
# 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 hour"
ExpiresByType application/x-javascript "now plus 2hours"
ExpiresByType application/javascript "now plus 2 hours"
ExpiresByType application/x-shockwave-flash "now plus 2hours"
ExpiresDefault "now plus 0 min"
< /IfModule>

检测语句:
# /usr/local/apache2/bin/apachectl -t
Syntax OK
重加载配置:
# /usr/local/apache2/bin/apachectl graceful

使用curl命令测试:
# echo 'asdadasdasd'>aaa.txt //在网站目录下创建txt文件
# touch abcd.jpeg //创建jpeg文件
# curl -u aming:123456 -x127.0.0.1:80 www.1.com/aaa.txt -I
HTTP/1.1 200 OK
Date: Fri, 31 Jul 2015 14:46:52 GMT
Server: Apache/2.4.12 (Unix) PHP/5.5.5
Last-Modified: Fri, 31 Jul 2015 14:46:00 GMT
ETag: "c-51c2ce0e6cdbe"
Accept-Ranges: bytes
Content-Length: 12
Cache-Control: max-age=0
Expires: Fri, 31 Jul 2015 14:46:52 GMT
Content-Type: text/plain

# curl -u aming:123456 -x127.0.0.1:80 www.1.com/abcd.jpeg -I
HTTP/1.1 200 OK
Date: Fri, 31 Jul 2015 14:47:43 GMT
Server: Apache/2.4.12 (Unix) PHP/5.5.5
Last-Modified: Fri, 31 Jul 2015 14:47:30 GMT
ETag: "0-51c2ce6388f1e"
Accept-Ranges: bytes
Cache-Control: max-age=86400
Expires: Sat, 01 Aug 2015 14:47:43 GMT
Content-Type: image/jpeg

说明配置完成!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  linux apache