當 PHP 動態輸出圖片、CSS、JS 等靜態資源時,若無快取機制,瀏覽器每次請求都返回 200 OK 並重複傳輸內容,造成頻寬浪費與伺服器壓力。透過 HTTP 快取頭資訊(ETag、Last-Modified)可讓瀏覽器在資源未變更時直接使用本地快取,返回 304 Not Modified 狀態碼,大幅提升效能。
| 機制 | 請求頭 | 回應頭 | 比對邏輯 |
|---|---|---|---|
| Last-Modified | If-Modified-Since | Last-Modified | 比對檔案修改時間戳 |
| ETag | If-None-Match | ETag | 比對檔案內容雜湊值(更精確) |
<?php
class StaticFileServer {
/**
* 輸出靜態檔案並支援 304 快取
* @param string $file 檔案絕對路徑
* @param string $mimeType MIME 類型,預設自動偵測
*/
public static function serve($file, $mimeType = '') {
if (!is_file($file) || !is_readable($file)) {
header("HTTP/1.1 404 Not Found");
exit('File not found');
}
$lastModified = filemtime($file);
$etag = md5_file($file); // 也可用 sprintf('%x-%x-%x', $lastModified, filesize($file), fileinode($file))
// 發送快取驗證頭
header("Last-Modified: " . gmdate("D, d M Y H:i:s", $lastModified) . " GMT");
header("ETag: \"{$etag}\"");
header("Cache-Control: public, max-age=3600"); // 1 小時強制快取
// 檢查客戶端快取是否有效
$clientModified = isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])
? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE'])
: 0;
$clientEtag = isset($_SERVER['HTTP_IF_NONE_MATCH'])
? trim($_SERVER['HTTP_IF_NONE_MATCH'], '"')
: '';
if ($clientModified == $lastModified || $clientEtag === $etag) {
header("HTTP/1.1 304 Not Modified");
exit;
}
// 輸出檔案內容
if ($mimeType) {
header("Content-Type: {$mimeType}");
}
header("Content-Length: " . filesize($file));
readfile($file);
}
}
// 使用範例:輸出圖片
// StaticFileServer::serve('/var/www/images/photo.jpg', 'image/jpeg');
?>
inode-size-mtime 組合,效能極佳,但若透過複製檔案覆蓋可能導致 inode 不變而誤判md5_file(),大檔案用屬性組合// 強制快取 1 年(適用版本化靜態資源,如 app.v2.css)
header("Cache-Control: public, max-age=31536000, immutable");
// 協商快取(適用動態輸出資源)
header("Cache-Control: public, must-revalidate");
$file 路徑,防止目錄遍歷攻擊(../etc/passwd)realpath() 正規化路徑並確認在允許目錄內Content-Type 防止 MIME 嗅探攻擊生產環境建議讓 Web Server 直接處理靜態檔案,PHP 僅處理需權限控管、動態產生、壓縮轉檔等場景:
# Nginx 設定範例
location /protected-images/ {
internal; # 僅允許內部重導向
alias /var/www/protected/; # 實際檔案目錄
}
# PHP 中透過 X-Accel-Redirect 交給 Nginx 輸出
header("X-Accel-Redirect: /protected-images/photo.jpg");
header("Content-Type: image/jpeg");
exit;
正確實作 304 快取機制能顯著降低頻寬消耗與伺服器負載。關鍵在於:正確生成 ETag/Last-Modified、完整處理請求頭比對邏輯、搭配適當的 Cache-Control 策略。生產環境優先考慮讓 Web Server 原生處理靜態資源快取。