Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 靜態資源快取配置:mod_expires 完整指南

編輯:關於伺服器

啟用模組

# httpd.conf 取消註釋
LoadModule expires_module modules/mod_expires.so

核心配置範例(建議放入 VirtualHost 或 Directory)

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 days"
    
    # CSS/JS 快取 14 天
    ExpiresByType text/css "access plus 14 days"
    ExpiresByType text/javascript "access plus 14 days"
    ExpiresByType application/javascript "access plus 14 days"
    ExpiresByType application/x-javascript "access plus 14 days"
    
    # 圖片/媒體快取 14 天
    ExpiresByType image/jpeg "access plus 14 days"
    ExpiresByType image/png "access plus 14 days"
    ExpiresByType image/gif "access plus 14 days"
    ExpiresByType image/webp "access plus 14 days"
    ExpiresByType image/svg+xml "access plus 14 days"
    ExpiresByType video/mp4 "access plus 14 days"
    ExpiresByType audio/mpeg "access plus 14 days"
    
    # 字體檔案
    ExpiresByType font/woff "access plus 14 days"
    ExpiresByType font/woff2 "access plus 14 days"
    ExpiresByType application/font-woff2 "access plus 14 days"
    
    # 特定副檔名強制長期快取
    <FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
        ExpiresDefault "access plus 1 year"
    </FilesMatch>
    
    # HTML 不快取或短快取(視業務調整)
    ExpiresByType text/html "access plus 1 hour"
</IfModule>

參數語法說明

語法含義
access plus N days從存取時間起算 N 天
modification plus N days從檔案修改時間起算
A86400秒數表示(86400=1天)
M2592000修改時間起算秒數

搭配 mod_headers 強化控制(推薦)

<IfModule mod_headers.c>
    # 靜態資源添加公共快取標頭
    <FilesMatch "\.(css|js|jpg|jpeg|png|gif|ico|woff|woff2)$">
        Header set Cache-Control "public, max-age=1209600, immutable"
    </FilesMatch>
    
    # HTML 私有快取,需驗證
    <FilesMatch "\.html$">
        Header set Cache-Control "private, must-revalidate"
    </FilesMatch>
</IfModule>

驗證方式

# curl 檢查回應標頭
curl -I https://example.com/style.css
# 預期看到:
# Cache-Control: max-age=1209600
# Expires: Wed, 15 Jan 2025 08:00:00 GMT

避坑指南

  • 動態頁面 (PHP/JSP/ASP.NET) 勿設定長期 Expires,否則內容更新不生效
  • 版本化靜態資源 (如 style.v202501.css) 可安心設長期快取
  • CDN 節點會遵循 Expires/Cache-Control,配置前確認 CDN 設定不衝突
  • 開發階段建議關閉快取或使用 ?v=timestamp 強制刷新

效能影響

正確配置瀏覽器快取可減少 60-80% 重複請求,大幅降低伺服器頻寬與 CPU 壓力,提升首屏載入速度。

Copyright © Windows教程網 All Rights Reserved