在服务器端可以配置Apache静态缓存,让客户端浏览器缓存一段时间(几个小时或几天)该页面中的静态元素,如一些小图片,样式等等,这样可以让用户每次访问请求中不需要重复传输这些静态元素,以减少每次访问的带宽,提高访问速度。
1.编辑虚拟主机配置文件:
[[email protected] logs]# vim /usr/local/apache2/conf/extra/httpd-vhosts.conf
2.加入如下配置:指定格式文件在浏览器中缓存的时间
……
SetEnvIf Request_URI "\.jpg$" image-request
SetEnvIf Request_URI "\.png$" image-request
SetEnvIf Request_URI "\.bmp$" image-request
SetEnvIf Request_URI "\.swf$" image-request
SetEnvIf Request_URI "\.js$" image-request
SetEnvIf Request_URI "\.css$" image-request
CustomLog "| /usr/local/apache2/bin/rotatelogs -l /usr/local/apache2/logs/test.com-access_%Y%m%d_log 86400" combined env=!image-request
<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 image/css "now plus 2 hours"
ExpiresByType application/x-javascript "now plus 2 hours"
ExpiresByType application/x-shockwave-flash "now plus 2 hours"
ExpiresDesfault "now plus 0 min"
</IfModule>
<IfModule mod_rewrite.c>
……
3.检查没错就重启
[[email protected] logs]# apachectl -t
Syntax OK
[[email protected] logs]# apachectl graceful
4.使用curl命令测试一张我们网站里的png图片,可以看到我们上面的配置成功了,86400秒==24小时==1天:
[[email protected] logs]# curl -x127.0.0.1:80 ‘http://www.test.com/static/image/common/logo_88_31.gif‘ -I
HTTP/1.1 200 OK
Date: Wed, 11 Jan 2017 14:15:37 GMT
Server: Apache/2.2.9 (Unix) PHP/5.4.36
Last-Modified: Tue, 31 May 2016 03:08:36 GMT
ETag: "dfbad-9e0-5341ab0597500"
Accept-Ranges: bytes
Content-Length: 2528
Cache-Control: max-age=86400
Expires: Thu, 12 Jan 2017 14:15:37 GMT
Content-Type: image/gif