高併發動態頁面頻繁查詢數據庫,導致服務器負載過高。生成靜態 HTML 文件,讓 Web 服務器(Nginx/Apache)直接服務靜態文件,繞過 PHP 與數據庫,極大提升吞吐量。
/**
* 生成靜態 HTML 緩存文件
* @param string $root 靜態文件存放根目錄(需可寫)
* @param string $rule 文件命名規則(如 'article_123')
* @param string $url 動態頁面完整 URL(將被請求並保存輸出)
* @return bool|int 寫入字節數或 false
*/
public function setHtmlCache($root, $rule, $url) {
$filePath = $root . $rule . '.html';
// 檢測是否已存在,存在則刪除重新生成(簡單覆蓋策略)
if (file_exists($filePath)) {
@unlink($filePath);
}
// 獲取動態頁面輸出內容
$content = file_get_contents($url);
if ($content === false) {
// 記錄錯誤日誌
error_log("Static cache generation failed for URL: $url");
return false;
}
// 寫入文件(原子寫入:寫臨時文件 rename,防止讀到半寫文件)
$tmpFile = $filePath . '.tmp.' . mt_rand();
$bytes = file_put_contents($tmpFile, $content);
if ($bytes === false) {
@unlink($tmpFile);
return false;
}
@rename($tmpFile, $filePath); // 原子操作
return $bytes;
}
<?php
// 控制器中
$htmlCache = new HtmlCache(); // 假設類名
$root = '/var/www/html/static_cache/'; // Nginx 靜態文件根目錄下的子目錄
$rule = 'article_' . $articleId;
$url = 'https://example.com/article/detail?id=' . $articleId;
if ($htmlCache->setHtmlCache($root, $rule, $url)) {
echo "靜態緩存生成成功:$rule.html";
} else {
echo "生成失敗";
}
?>
location / {
# 嘗試直接服務靜態緩存文件
try_files /static_cache/$uri.html /static_cache/$uri @php_fallback;
}
location @php_fallback {
# 無靜態文件時反向代理到 PHP-FPM
proxy_pass https://php_backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
expires 指令配合)。gzip_static on,預壓縮 .gz 文件。www-data 用戶)。basename、realpath 校驗)。