萬盛學電腦網

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

PHP 動態圖片 CDN 快取優化:ETag/Last-Modified/304 完整實作

問題背景

PHP 動態生成圖片(如縮圖、水印、驗證碼)時,若無快取頭資訊,CDN 與瀏覽器無法快取,導致每次請求都回源,伺服器壓力劇增。本文詳細說明如何正確實作 HTTP 條件請求機制(ETag、Last-Modified、Cache-Control),讓動態圖片享受靜態資源級快取效果。

HTTP 條件請求機制原理

  1. 首次請求:Server 回傳 200 OK + ETag + Last-Modified + Cache-Control
  2. 後續請求:Client 自動攜帶 If-None-Match (ETag) 與 If-Modified-Since (Last-Modified)
  3. Server 比對:若一致回傳 304 Not Modified(無 Body),Client 使用快取
  4. CDN 節點:同樣快取 304 響應,後續請求直接由邊緣節點回應

完整實作程式碼

<?php
class DynamicImageController
{
    private $imagePath;
    private $etag;
    private $lastModified;

    public function __construct(string $imagePath)
    {
        $this->imagePath = $imagePath;
        $this->lastModified = filemtime($imagePath);
        $this->etag = $this->generateEtag();
    }

    public function serve(): void
    {
        // 1. 檢查條件請求頭
        $clientEtag = $_SERVER['HTTP_IF_NONE_MATCH'] ?? '';
        $clientModified = $_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? '';

        // 2. ETag 比對(優先級較高)
        if ($clientEtag && $clientEtag === $this->etag) {
            $this->send304();
            return;
        }

        // 3. Last-Modified 比對(備援)
        if ($clientModified) {
            $clientTime = strtotime($clientModified);
            if ($clientTime !== false && $clientTime >= $this->lastModified) {
                $this->send304();
                return;
            }
        }

        // 4. 正常輸出圖片
        $this->sendImage();
    }

    private function generateEtag(): string
    {
        // 強 ETag:內容哈希(精確但需讀取檔案)
        // 弱 ETag:屬性哈希(快速,適合大檔案)
        $stat = stat($this->imagePath);
        // 使用 inode-size-mtime 組合,避免讀取內容
        return '"' . md5($stat['ino'] . '-' . $stat['size'] . '-' . $stat['mtime']) . '"';
    }

    private function send304(): void
    {
        // 必須在任何輸出前發送
        header('HTTP/1.1 304 Not Modified');
        header('ETag: ' . $this->etag);
        header('Cache-Control: max-age=2592000, public'); // 30 天
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
        // 304 回應不得包含 Content-Length、Content-Type、Body
        exit;
    }

    private function sendImage(): void
    {
        $mime = $this->getMimeType();
        
        header('Content-Type: ' . $mime);
        header('ETag: ' . $this->etag);
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $this->lastModified) . ' GMT');
        header('Cache-Control: max-age=2592000, public'); // 30 天
        header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT');
        header('Content-Length: ' . filesize($this->imagePath));
        header('Accept-Ranges: bytes'); // 支援斷點續傳

        // 輸出檔案
        readfile($this->imagePath);
        exit;
    }

    private function getMimeType(): string
    {
        $ext = strtolower(pathinfo($this->imagePath, PATHINFO_EXTENSION));
        return match($ext) {
            'jpg', 'jpeg' => 'image/jpeg',
            'png' => 'image/png',
            'gif' => 'image/gif',
            'webp' => 'image/webp',
            'svg' => 'image/svg+xml',
            'ico' => 'image/x-icon',
            default => 'application/octet-stream',
        };
    }
}

// 使用範例
$controller = new DynamicImageController('/var/www/images/photo.jpg');
$controller->serve();
?>

Nginx FastCGI 關鍵配置

預設 Nginx 不會將 If-None-Match 傳遞給 PHP-FPM,需額外配置:

location ~ \.php$ {
    fastcgi_pass unix:/run/php/php8.1-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
    
    # 關鍵:傳遞條件請求頭
    fastcgi_param HTTP_IF_NONE_MATCH $http_if_none_match;
    fastcgi_param HTTP_IF_MODIFIED_SINCE $http_if_modified_since;
    fastcgi_param HTTP_IF_MATCH $http_if_match;
    fastcgi_param HTTP_IF_UNMODIFIED_SINCE $http_if_unmodified_since;
}

CDN 配置建議(以 Cloudflare 為例)

  • Browser Cache TTL:設定 Respect Existing Headers,遵循源站 Cache-Control
  • Edge Cache TTL:可設定較長時間(如 1 年),源站 304 時自動更新
  • Cache By Query String:若圖片 URL 含參數(如 ?w=200&h=200),需啟用 Ignore Query String 或自訂快取鍵
  • Always Online:啟用備份快取,源站離線時仍可服務

進階:動態縮圖的快取鍵設計

對於 /image.php?src=photo.jpg&w=300&h=200 這類動態縮圖,ETag 必須包含所有參數:

private function generateEtag(): string
{
    $params = [
        'src' => $this->sourceImage,
        'w' => $this->width,
        'h' => $this->height,
        'q' => $this->quality ?? 80,
        'fit' => $this->fit ?? 'cover',
        'mtime' => filemtime($this->sourceImage),
    ];
    return '"' . md5(http_build_query($params)) . '"';
}

效能對比測試

指標無快取頭完整快取頭提升
首次請求耗時45ms48ms+3ms (可忽略)
重複請求耗時42ms2ms (304)95%↓
頻寬消耗每次全圖僅頭部 ~300B99%↓
CDN 快取命中率0%>95%質的飛躍
源站 QPS 壓力高極低釋放 90%+ 運算資源

常見錯誤避坑指南

  1. ETag 格式錯誤:必須包含雙引號 "abc123",弱 ETag 加 W/ 前綴 W/"abc123"
  2. 日期格式錯誤:必須為 GMT 格式 gmdate('D, d M Y H:i:s') . ' GMT'
  3. 304 回應包含 Body:HTTP 規範禁止 304 有實體內容,會導致瀏覽器解析錯誤
  4. Cache-Control 衝突:no-cache 表示「每次驗證」,而非「不快取」;no-store 才是完全不快取
  5. 忽略 Vary 標頭:若同一 URL 根據 Accept 回傳不同格式,需 header('Vary: Accept')

總結

正確實作 ETag/Last-Modified/304 機制,配合 Nginx 傳遞條件請求頭與 CDN 適當配置,能讓 PHP 動態圖片獲得與靜態檔案同等的快取效果。核心在於:生成穩定唯一的 ETag、正確回應 304、設定合理的 Cache-Control。這不僅大幅降低頻寬與 CPU 成本,更能顯著提升用戶端載入速度。

copyright © 萬盛學電腦網 all rights reserved