設置網站expires和max-age屬性


轉:http://www.zicheng.net/article/982022.htm

在使用百度站長工具測試網站優化建議時,在 設置靜態內容緩存時間 欄目里,會提示 類似 FAILED - (未設置max-age或expires) - http://www.zicheng.net 的內容,我也是遇到同樣的問題,經過多次搜索最終找到解決辦法,先分別就在nignx、tomcat以及apache中如何設置max-age或expires參數進行簡單的講解。

分為三塊來講,針對apache,tomcat,nginx

1. apache設置max-age或expires

這里需要修改.htaccess文件。

<IfModule mod_headers.c>

    <FilesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|js|css|swf)$">

        Header set Cache-Control "max-age=604800, public"

    </FilesMatch>

<FilesMatch "\.(xml|txt)$">

    Header set Cache-Control "max-age=18000, public, must-revalidate"

</FilesMatch>

<FilesMatch "\.(html|htm|php|shtml)$">

    Header set Cache-Control "max-age=3600, must-revalidate"

</FilesMatch>

</IfModule>

2. tomcat中設置max-age或expires

首先pom.xml需要引入catalina包,如果不是使用的maven,請自行搜索下載jar包


<dependency>

   <groupId>org.apache.tomcat</groupId>

   <artifactId>tomcat-catalina</artifactId>

   <version>7.0.61</version>

</dependency>

注意,版本必須是7.0.61以上的,如果你不是maven需要引入jar包及相關的依賴包。

其次,然后找到你j2ee項目中的web.xml文件,在文件中加入如下內容


  <filter>

      <filter-name>ExpiresFilter</filter-name>

      <filter-class>org.apache.catalina.filters.ExpiresFilter</filter-class>

      <init-param>

          <param-name>ExpiresByType text/html</param-name>

          <param-value>access plus 1 minutes</param-value>

      </init-param>

      <init-param>

          <param-name>ExpiresByType image</param-name>

          <param-value>access plus 10 years</param-value>

      </init-param>

      <init-param>

          <param-name>ExpiresByType text/css</param-name>

          <param-value>access plus 10 months</param-value>

      </init-param>

      <init-param>

          <param-name>ExpiresByType application/javascript</param-name>

          <param-value>access plus 10 months</param-value>

      </init-param>

      <init-param>

          <param-name>ExpiresByType application/x-unknown-content-type</param-name>

          <param-value>access plus 10 years</param-value>

      </init-param>

  </filter>

  <filter-mapping>

      <filter-name>ExpiresFilter</filter-name>

      <url-pattern>/*</url-pattern>

      <dispatcher>REQUEST</dispatcher>

    </filter-mapping>

以上內容分別對js腳本、css樣式、圖片以及html頁面進行了緩存設置。

其中param-value的值可以設置為比如 access plus 1 month 15 days 2 hours

不可以使用以下的任意的類型或類型組合,(這個我沒看懂!~)

years
months
weeks
days
hours
minutes
seconds

PS:再次提醒catalina的版本要7.0.61以上的才行,低版本里未實現filters.ExpiresFilter類。

3.nginx設置max-age或expires

在server節點下加入如下代碼


  location  ~* \.(gif|jpg|png|bmp)$ {

   expires 10d;

  }

這里是設置圖片的過期時間為10天。如果你的圖片基本不更新可以設置的時間長一些。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM