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 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>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章