萬盛學電腦網

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

PHP 靜態資源輸出優化:利用 ETag 與 Last-Modified 實現 304 快取

問題背景

當 PHP 動態輸出圖片、CSS、JS 等靜態資源時,若無快取機制,瀏覽器每次請求都返回 200 OK 並重複傳輸內容,造成頻寬浪費與伺服器壓力。透過 HTTP 快取頭資訊(ETag、Last-Modified)可讓瀏覽器在資源未變更時直接使用本地快取,返回 304 Not Modified 狀態碼,大幅提升效能。

核心原理

機制請求頭回應頭比對邏輯
Last-ModifiedIf-Modified-SinceLast-Modified比對檔案修改時間戳
ETagIf-None-MatchETag比對檔案內容雜湊值(更精確)

完整實現程式碼

<?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');
?>

關鍵細節說明

1. ETag 生成策略

  • md5_file():內容級雜湊,檔案內容變更必然改變 ETag,最可靠但大檔案計算較慢
  • 檔案屬性組合:inode-size-mtime 組合,效能極佳,但若透過複製檔案覆蓋可能導致 inode 不變而誤判
  • 建議:小檔案用 md5_file(),大檔案用屬性組合

2. 快取頭最佳實踐

// 強制快取 1 年(適用版本化靜態資源,如 app.v2.css)
header("Cache-Control: public, max-age=31536000, immutable");

// 協商快取(適用動態輸出資源)
header("Cache-Control: public, must-revalidate");

3. 安全性考量

  • 嚴格驗證 $file 路徑,防止目錄遍歷攻擊(../etc/passwd)
  • 使用 realpath() 正規化路徑並確認在允許目錄內
  • 設定 Content-Type 防止 MIME 嗅探攻擊

Nginx/Apache 整合建議

生產環境建議讓 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 原生處理靜態資源快取。

copyright © 萬盛學電腦網 all rights reserved