Web 請求處理鏈路:瀏覽器 → CDN → Nginx → PHP-FPM → MySQL/Redis。每一層都可引入緩存,層層遞減後端壓力。本文系統梳理 PHP 相關的四大緩存層:瀏覽器緩存、PHP Opcode 緩存、應用層資料緩存、HTTP 反向代理緩存。
| 標頭 | 作用 | 範例值 |
|---|---|---|
Cache-Control | 主要控制指令 | max-age=3600, public, must-revalidate |
Expires | 絕對過期時間 (HTTP/1.0 相容) | Wed, 21 Oct 2025 07:28:00 GMT |
Last-Modified | 資源最後修改時間 | Wed, 20 Oct 2025 12:00:00 GMT |
ETag | 資源實體標籤 (強/弱驗證) | "abc123-deadbeef" |
Vary | 指定內容協商依據 | Accept-Encoding, Cookie |
<?php
// 靜態資源長期緩存 (1年) + 內容變更即失效 (ETag)
$file = __DIR__ . '/assets/app.js';
$etag = '"' . md5_file($file) . '"';
$lastMod = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT';
header('Cache-Control: max-age=31536000, public, immutable');
header('ETag: ' . $etag);
header('Last-Modified: ' . $lastMod);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 31536000) . ' GMT');
// 處理條件請求
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) && $_SERVER['HTTP_IF_NONE_MATCH'] === $etag) {
http_response_code(304);
exit;
}
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
http_response_code(304);
exit;
}
readfile($file);
<?php
// 動態頁面:短期緩存 + 必須重新驗證
header('Cache-Control: max-age=60, must-revalidate, private');
header('Vary: Accept-Encoding, Cookie'); // 不同壓縮/登入狀態分開緩存
header('ETag: ' . '"' . md5(serialize($pageData)) . '"');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $lastUpdateTime) . ' GMT');
// 條件請求檢查
$etag = '"' . md5(serialize($pageData)) . '"';
if (($_SERVER['HTTP_IF_NONE_MATCH'] ?? '') === $etag) {
http_response_code(304);
exit;
}
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache'); // HTTP/1.0 相容
header('Expires: Thu, 01 Jan 1970 00:00:00 GMT');
PHP 5.5+ 內建,將編譯後的 opcode 存入共享記憶體,省去每次請求的「解析→編譯」過程,典型提升 2-10 倍吞吐量。
; 啟用
opcache.enable=1
opcache.enable_cli=1
; 共享記憶體大小 (視專案代碼量調整,建議 256MB-1GB)
opcache.memory_consumption=512
; 內部字串緩存
opcache.interned_strings_buffer=64
; 最大緩存檔案數 (設大於專案 PHP 檔案總數)
opcache.max_accelerated_files=20000
; 檢查腳本更新頻率 (0=每次請求檢查、生產環境建議 60-300 秒、0 開發環境)
opcache.revalidate_freq=60
; 快速關閉 (請求結束不釋放鎖,加速)
opcache.fast_shutdown=1
; 開啟優化等級 (預設 0x7FFFBFFF 全開)
opcache.optimization_level=0x7FFFBFFF
; 預載入 (PHP 7.4+) - 將常用類別/函式預載入記憶體
opcache.preload=/var/www/html/preload.php
opcache.preload_user=www-data
<?php
// 使用 opcache_compile_file 預編譯核心框架類別
$coreFiles = glob(__DIR__ . '/vendor/laravel/framework/src/Illuminate/**/*.php');
foreach ($coreFiles as $file) {
opcache_compile_file($file);
}
// 或使用 Composer 生成的 class map
$map = require __DIR__ . '/vendor/composer/autoload_classmap.php';
foreach ($map as $file) {
if (strpos($file, 'vendor/') !== false) opcache_compile_file($file);
}
opcache_get_status() 或安裝 opcache-gui、cachetool。opcache_reset() 或重啟 PHP-FPM,或使用 cachetool opcache:reset。| 特性 | Redis | Memcached | APCu |
|---|---|---|---|
| 資料結構 | 豐富 (String, Hash, List, Set, SortedSet, Stream, Geo, Bitmap) | 單純 Key-Value | 單純 Key-Value |
| 持久化 | RDB/AOF 可選 | 無 (純記憶體) | 無 (PHP 進程生命週期) |
| 叢集/高可用 | 原生 Cluster、Sentinel | Client-side 一致性哈希 | 單機 (PHP-FPM 多進程共享) |
| 適用場景 | 通用首選:Session、快取、佇列、鎖、排行榜、限流 | 極簡 Key-Value、超大值 (>1MB)、多線程高並發 | 單機小型應用、Opcode 以外的本地熱數據 |
<?php
// 使用 phpredis 擴展 (效能最佳) 或 predis/predis (純 PHP)
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->setOption(Redis::OPT_SERIALIZER, Redis::SERIALIZER_IGBINARY); // 高效序列化
$redis->setOption(Redis::OPT_PREFIX, 'myapp:'); // 統一前綴避免衝突
// 封裝通用快取類
class Cache {
private Redis $redis;
public function __construct(Redis $redis) { $this->redis = $redis; }
public function get(string $key, mixed $default = null): mixed {
$val = $this->redis->get($key);
return $val === false ? $default : $val;
}
public function set(string $key, mixed $value, int $ttl = 3600): bool {
return $this->redis->setex($key, $ttl, $value);
}
public function remember(string $key, int $ttl, callable $callback): mixed {
if (($val = $this->get($key)) !== null) return $val;
$val = $callback();
$this->set($key, $val, $ttl);
return $val;
}
public function delete(string $key): bool { return (bool)$this->redis->del($key); }
public function flush(): bool { return $this->redis->flushDB(); }
}
// 使用
$cache = new Cache($redis);
$user = $cache->remember("user:{$userId}", 300, fn() => User::find($userId));
$ttl + rand(0, 300)) + 多級緩存。# nginx.conf http 區塊
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 keys_zone=PHPCACHE:100m inactive=60m max_size=1g;
# server 區塊
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.2-fpm.sock;
fastcgi_cache PHPCACHE;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_valid 200 301 302 5m; # 成功頁面緩存 5 分鐘
fastcgi_cache_valid 404 1m; # 404 緩存 1 分鐘
fastcgi_cache_use_stale error timeout updating http_500 http_503;
fastcgi_cache_bypass $http_cache_control; # 客戶端送 no-cache 時繞過
fastcgi_no_cache $http_cache_control;
add_header X-Cache-Status $upstream_cache_status; # HIT/MISS/BYPASS/EXPIRED
include fastcgi_params;
}
; php.ini / .user.ini
zlib.output_compression = On
zlib.output_compression_level = 6 ; 1-9,6 平衡 CPU/壓縮率
; 或 Nginx gzip (推薦由 Web Server 處理,卸載 PHP CPU)
# nginx.conf
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_comp_level 6;
app.v20240115.js 或 app.[contenthash].js (Webpack/Vite 自動生成),長期強緩存 (Cache-Control: max-age=31536000, immutable)。高性能 PHP 架構 = OPcache (必開) + 瀏覽器緩存 (正確標頭) + Redis 應用層緩存 (業務熱點) + Nginx fastcgi_cache/CDN (全頁/片段緩存) + 資源版本化壓縮。各層職責清晰、失效策略明確、監控告警完備,即可支撐百萬級日活、毫秒級響應的現代化 PHP 應用。