萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

深入解析 HTTP 快取控制標頭與常用 Header 指令

HTTP 快取機制是網頁效能優化的核心環節,主要透過回應標頭中的 Cache-Control 指令來控制。常見指令包括 private、no-cache、max-age、must-revalidate 等,預設值為 private。其行為會因使用者的重新瀏覽方式(開新視窗、網址列按 Enter、按上一頁、按重新整理)而有所不同。

各種重新瀏覽情境下的快取行為

1. 開啟新視窗

  • 值為 private、no-cache、must-revalidate:每次都會重新向伺服器請求。
  • 指定 max-age(例如 Cache-Control: max-age=5):在指定秒數內不會重新請求伺服器。

2. 在網址列按 Enter

  • private 或 must-revalidate:僅第一次請求伺服器,之後不再請求。
  • no-cache:每次都會請求。
  • max-age:在過期前不會重複請求。

3. 按下「上一頁」按鈕

  • private、must-revalidate、max-age:不會重新請求。
  • no-cache:每次都會重新請求。

4. 按下「重新整理」按鈕

  • 無論 Cache-Control 為何值,都會強制重新請求伺服器。

禁止頁面在 IE 中快取的完整設定

CacheControl = no-cache
Pragma = no-cache
Expires = -1

Expires 設為過去時間(如 Fri, 31 Dec 1999 16:00:00 GMT)可強制每次重新請求。若頁面每日固定時間更新,可設定為下一次更新時間點。

注意:HTTP 1.0 伺服器不支援 Cache-Control,為相容需加上 Pragma: no-cache。但在非安全連線(非 HTTPS)下,Pragma: no-cache 效果等同 Expires: -1,頁面仍會被快取但標記為立即過期;唯有在 HTTPS 連線下才真正防止快取。

PHP Header 常用指令速查

HTTP 回應標頭分為三部分:協定版本、狀態碼、原因短語。以下整理常用 header() 指令:

狀態碼控制

// 修正 URL 重寫導致的 404
header('HTTP/1.1 200 OK');

// 明確回傳 404
header('HTTP/1.1 404 Not Found');

// 永久重導向(利於 SEO)
header('HTTP/1.1 301 Moved Permanently');
header('Location: https://example.com/new-url');

// 存取受限
header('HTTP/1.1 403 Forbidden');

// 伺服器錯誤
header('HTTP/1.1 500 Internal Server Error');

// 延遲重導向
header('Refresh: 10; url=https://example.com');
echo '10 秒後將自動跳轉...';

快取控制

// 禁止快取(完整設定)
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');

// 利用 Last-Modified 與 304 Not Modified 實現條件式請求
$time = time() - 60;
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $time) . ' GMT');
header('HTTP/1.1 304 Not Modified');

// 設定內容長度(利於快取)
header('Content-Length: 1234');

內容類型與下載

// 覆蓋 X-Powered-By
header('X-Powered-By: PHP/8.2');

// 內容語言
header('Content-language: zh-TW');

// 設定字元編碼
header('Content-Type: text/html; charset=utf-8');

// 檔案下載範例
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="example.zip"');
header('Content-Transfer-Encoding: binary');
readfile('example.zip');

// 常見 MIME 類型
header('Content-Type: text/plain');           // 純文字
header('Content-Type: image/jpeg');           // JPG 圖片
header('Content-Type: application/zip');      // ZIP 檔案
header('Content-Type: application/pdf');      // PDF 文件
header('Content-Type: audio/mpeg');           // MP3 音訊
header('Content-Type: application/x-shockwave-flash'); // Flash

HTTP 認證

header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');
echo '取消或輸入錯誤帳密時顯示的文字';
copyright © 萬盛學電腦網 all rights reserved