善用 HTTP 快取頭部(Last-Modified、ETag、Expires、Cache-Control)能大幅減少頻寬、降低延遲、減輕伺服器壓力。本文深入原理並給出生產級 Web Server 配置範例。
Last-Modified: Fri, 12 May 2006 18:53:33 GMTIf-Modified-Since: Fri, 12 May 2006 18:53:33 GMTETag: "50b1c1d4f775c61:df3")。If-None-Match: "50b1c1d4f775c61:df3"W/ 前綴表弱驗證(語義相等即可),無前綴為強驗證(位元組完全相同)。Expires: Thu, 02 Apr 2009 05:14:08 GMT:絕對過期時間(HTTP/1.0)。Cache-Control: max-age=2592000:相對秒數(HTTP/1.1,**優先級高於 Expires**)。public/private/no-cache/no-store/must-revalidate 等指令精細控制快取行為。Last-Modified + ETag + Cache-Control。If-Modified-Since + If-None-Match → Server 比對 → 304 或 200 新資源。<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType text/html "access plus 0 seconds"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/javascript "access plus 1 year"
ExpiresByType image/gif "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType image/webp "access plus 1 year"
ExpiresByType image/x-icon "access plus 1 year"
ExpiresByType application/font-woff2 "access plus 1 year"
</IfModule>
# ETag 預設開啟(inode mtime size),可微調
<IfModule mod_headers.c>
# 靜態資源加強快取
<FilesMatch "\.(css|js|png|jpg|jpeg|gif|webp|ico|woff2?)$">
Header append Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>
# HTML 不快取或短快取
<FilesMatch "\.html$">
Header append Cache-Control "public, max-age=0, must-revalidate"
</FilesMatch>
</IfModule>
# http 或 server 區塊
etag on; # 預設開啟
# 靜態資源長期強快取
location ~* \.(css|js|png|jpg|jpeg|gif|webp|ico|woff2?)$ {
expires 1y;
add_header Cache-Control "public, immutable";
# 可選:關閉 Last-Modified/ETag 避免驗證請求(需配合檔名哈希版本控制)
# etag off;
# add_header Last-Modified "";
}
# HTML 短快取或不快取
location ~* \.html$ {
expires -1; # 或 0
add_header Cache-Control "no-store, no-cache, must-revalidate";
}
# 通用 gzip 壓縮
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
Cache-Control: public, max-age=31536000, immutable + **檔名含哈希**(如 app.a1b2c3.js),實現「永久快取、內容變更即檔名變更、自動失效」。Cache-Control: no-cache, must-revalidate + ETag/Last-Modified 協商快取。Vary: Accept-Encoding, Accept-Language 防止代理快取錯誤版本。精準配置快取策略,是前端效能優化 ROI 最高的投資之一。