X

Apache2 載入 Expires 的模組(mod_expires) 與 設定

設定 圖片 / CSS / Javascript 等靜態檔案的過期時間, 可以讓網頁下次 loading 的速度更快(直接從瀏覽器的 cache 拉), 也可以節省 頻寬 和 Apache 吐這些檔案所耗的資源.

首先需要 Enable apache expires module, 方法如下:

  • a2enmod expires # a2enmod, a2dismod - enable or disable an apache2 module
  • 或 cd /etc/apache2/mods-enabled/; ln -s ../mods-available/expires.load

哪些檔案要加入 Expire header 的, 做如下述的設定:

  • 於 .htaccess 加入

    ExpiresActive On
    ExpiresDefault "access plus 4 hours"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType text/css "access plus 1 day"
    ExpiresByType text/html A900
    ExpiresByType text/xml A14400
    ExpiresByType text/plain "access plus 1 hours"
    ExpiresByType image/gif "access plus 1 day"
    ExpiresByType image/jpg "access plus 1 day"
    ExpiresByType image/jpeg "access plus 1 day"
    ExpiresByType image/png "access plus 1 day"
    ExpiresByType image/bmp "access plus 1 day"
    ExpiresByType application/x-shockwave-flash A3600

  • 或 Apache 的設定檔加入

    <IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType text/css "access plus 1 day"
    ExpiresByType text/html A900
    ExpiresByType text/xml A14400
    ExpiresByType text/plain "access plus 1 hours"
    ExpiresByType image/gif "access plus 1 day"
    ExpiresByType image/jpg "access plus 1 day"
    ExpiresByType image/jpeg "access plus 1 day"
    ExpiresByType image/png "access plus 1 day"
    ExpiresByType image/bmp "access plus 1 day"
    ExpiresByType application/x-shockwave-flash A3600
    </IfModule>

上述 image/png, application/x-shockwave-flash 等 mime-type, 詳細的可見: /usr/share/doc/apache-common/examples/mime.types.gz (Debian 放在這邊)

測試設定檔是否正確

  1. /usr/sbin/apache2ctl configtest 或 /usr/sbin/apache2ctl -t # 測試 Apache 設定檔有沒有錯誤 (此/usr/sbin/apache2ctl 是 Debian Linux 的路徑)
  2. 看到 Syntax OK, 就可以 /etc/init.d/apache2 reload 囉~ 🙂

相關網頁

Tsung: 對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.
Related Post