萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

HTTP 快取核心機制:Last-Modified、ETag、Expires 原理與 Apache/Nginx 實戰配置

善用 HTTP 快取頭部(Last-Modified、ETag、Expires、Cache-Control)能大幅減少頻寬、降低延遲、減輕伺服器壓力。本文深入原理並給出生產級 Web Server 配置範例。

核心機制原理

1. Last-Modified / If-Modified-Since

  • **首次請求**:Server 回 200 OK + Last-Modified: Fri, 12 May 2006 18:53:33 GMT
  • **再次請求**:Client 送 If-Modified-Since: Fri, 12 May 2006 18:53:33 GMT
  • **未變更**:Server 回 304 Not Modified,空內文,省下傳輸體積。
  • **缺點**:秒級精度、檔案修改時間可能異步(多伺服器)、內容未變但時間變會誤判。

2. ETag / If-None-Match

  • **實體標籤**:Server 依內容生成指紋(如 ETag: "50b1c1d4f775c61:df3")。
  • **再次請求**:Client 送 If-None-Match: "50b1c1d4f775c61:df3"
  • **優點**:內容級精度、無視修改時間、支援斷點續傳範圍請求。
  • **弱/強驗證**:W/ 前綴表弱驗證(語義相等即可),無前綴為強驗證(位元組完全相同)。

3. Expires / Cache-Control

  • 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 等指令精細控制快取行為。

4. 協同工作流程

  1. Client 請求資源 A。
  2. Server 回 200 + 資源 + Last-Modified + ETag + Cache-Control。
  3. Client 快存資源與驗證頭。
  4. 再次請求:強快取期內(max-age 未過)→ 直接讀快取,**不發請求**(200 from memory/disk cache)。
  5. 強快取過期 → 發請求攜帶 If-Modified-Since + If-None-Match → Server 比對 → 304 或 200 新資源。

Apache 配置範例(mod_expires + mod_headers)

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

Nginx 配置範例

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

最佳實踐總結

  1. 靜態資源(CSS/JS/圖片/字體):Cache-Control: public, max-age=31536000, immutable + **檔名含哈希**(如 app.a1b2c3.js),實現「永久快取、內容變更即檔名變更、自動失效」。
  2. HTML/動態 API:Cache-Control: no-cache, must-revalidate + ETag/Last-Modified 協商快取。
  3. 關閉 ETag 陷阱:多伺服器叢集若 ETag 算法含 inode,會導致同一檔案不同節點 ETag 不一致 → 失效協商快取。解決:統一 ETag 算法(如僅用 mtime+size)或關閉 ETag 依賴 Last-Modified。
  4. Vary 標頭:對壓縮/語言協商資源加 Vary: Accept-Encoding, Accept-Language 防止代理快取錯誤版本。

精準配置快取策略,是前端效能優化 ROI 最高的投資之一。

copyright © 萬盛學電腦網 all rights reserved