| 類型 | 原理 | 優點 | 缺點 |
| 真靜態 | PHP 產生實體 .html 檔案 | 效能最佳、無 PHP 依賴 | 部署複雜、大量頁面生成耗時、需同步機制 |
| 偽靜態 | Web Server Rewrite 將靜態 URL 對應動態腳本 | 開發簡單、即時生效 | 每次請求仍經 PHP、效能較差 |
四大生成策略(真靜態)
策略一:模板引擎 + Output Buffering(推薦)
// 1. 開啟緩衝區
ob_start();
// 2. 載入模板並輸出(Smarty/Twig/Blade 原生 display)
$smarty->display('article.tpl');
// 3. 取得內容並寫入靜態檔
$html = ob_get_clean();
file_put_contents('/var/www/html/article/123.html', $html);
策略二:純 PHP 字串組裝
$html = '<html><head><title>'.$title.'</title></head>'
. '<body>'.$content.'</body></html>';
file_put_contents($path, $html);
策略三:Output Control 函數(手動控制)
ob_start();
include 'template/article.php'; // 模板內直接 echo 變數
$html = ob_get_contents();
ob_end_clean();
file_put_contents($file, $html);
策略四:NoSQL 快取(Memcached/Redis)準靜態化
$key = 'article:'.$id;
$html = $redis->get($key);
if (!$html) {
ob_start();
include 'template/article.php';
$html = ob_get_clean();
$redis->setex($key, 86400, $html); // 快取 1 天
}
echo $html;
注意:此為「快取」而非「靜態檔」,但效能接近,且支援集群、自動過期。
自動更新機制
- 後台編輯儲存時:呼叫生成函數,即時重建對應 HTML。
- 定時任務:Cron 每小時掃描「需更新」旗標,批次重建。
- 訪問時檢查:前端控制器先判斷靜態檔是否存在且未過期,否則觸發重建(策略三/四常用)。
部署建議
- 靜態檔存放於獨立目錄(
/var/www/html/static/),Nginx 直接 try_files。
- CDN 設定
Cache-Control: max-age=31536000, immutable,版本更新用檔名哈希區分。
- 大型站點採用「分佈式生成 + 訊息佇列」,避免單點阻塞。
- 上一篇文章: PHP 目錄操作實戰:遞迴掃描、檔案計數與資料夾大小計算
- 下一篇文章: PHP 實現多層巢狀留言板(無限階回覆)完整架構
Copyright ©
程式碼之家 All Rights Reserved