PHP 動態生成圖片(如縮圖、水印、驗證碼)時,若無快取頭資訊,CDN 與瀏覽器無法快取,導致每次請求都回源,伺服器壓力劇增。本文詳細說明如何正確實作 HTTP 條件請求機制(ETag、Last-Modified、Cache-Control),讓動態圖片享受靜態資源級快取效果。
200 OK + ETag + Last-Modified + Cache-ControlIf-None-Match (ETag) 與 If-Modified-Since (Last-Modified)304 Not Modified(無 Body),Client 使用快取<?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 不會將 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;
}
Respect Existing Headers,遵循源站 Cache-Control?w=200&h=200),需啟用 Ignore Query String 或自訂快取鍵對於 /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)) . '"';
}
| 指標 | 無快取頭 | 完整快取頭 | 提升 |
|---|---|---|---|
| 首次請求耗時 | 45ms | 48ms | +3ms (可忽略) |
| 重複請求耗時 | 42ms | 2ms (304) | 95%↓ |
| 頻寬消耗 | 每次全圖 | 僅頭部 ~300B | 99%↓ |
| CDN 快取命中率 | 0% | >95% | 質的飛躍 |
| 源站 QPS 壓力 | 高 | 極低 | 釋放 90%+ 運算資源 |
"abc123",弱 ETag 加 W/ 前綴 W/"abc123"gmdate('D, d M Y H:i:s') . ' GMT'no-cache 表示「每次驗證」,而非「不快取」;no-store 才是完全不快取Accept 回傳不同格式,需 header('Vary: Accept')正確實作 ETag/Last-Modified/304 機制,配合 Nginx 傳遞條件請求頭與 CDN 適當配置,能讓 PHP 動態圖片獲得與靜態檔案同等的快取效果。核心在於:生成穩定唯一的 ETag、正確回應 304、設定合理的 Cache-Control。這不僅大幅降低頻寬與 CPU 成本,更能顯著提升用戶端載入速度。