靜態化發布是高流量網站(如新聞門戶、部落格、CMS)提升效能的經典架構。本文系統性說明「動態管理、靜態發布」的核心流程、關鍵技術點與進階優化策略。
{title}, {content}, {date} 等) → 生成完整 HTML 字串2024/01/15/article-slug.html) → fwrite() 寫入靜態檔ob_start() + include,零依賴,效能最佳function generateSlug($title) {
// 中文標題轉拼音或保留 ID
return strtolower(trim(preg_replace('/[^a-z0-9\-]/', '-', pinyin($title)), '-'));
}
$filename = date('Y/m/d') . '/' . $articleId . '-' . generateSlug($title) . '.html';
// 例:2024/01/15/12345-wo-de-wen-zhang.html
/var/www/html/
├── static/ # 靜態頁根目錄(Nginx root 指向此處)
│ ├── 2024/01/15/
│ │ └── 12345-article.html
│ ├── category/
│ │ └── tech.html
│ ├── index.html
│ └── sitemap.xml
├── templates/ # 模板檔(不可 Web 存取)
└── admin/ # 後台程式
確保 static/ 目錄對 PHP 進程可寫(chown www-data:www-data static/),但禁止腳本執行(Nginx location ~ \.php$ { deny all; })。
避免全站重新生成,採用「影響範圍」機制:
// 發布時推入佇列而非同步生成
$redis->lpush('static_gen_queue', json_encode([
'action' => 'publish',
'article_id' => $id,
'affected_pages' => ['index', 'category/tech', 'tag/php', 'rss', 'sitemap']
]));
// Worker 進程消費
while (true) {
$task = $redis->brpop('static_gen_queue', 10);
if ($task) generateStaticPages(json_decode($task[1], true));
}
| 策略 | 說明 | 收益 |
|---|---|---|
| CDN 整合 | 靜態檔推送至 CDN,回源設定快取規則 | 全球加速、源站減壓 90%+ |
| 瀏覽器快取 | Nginx expires 30d; add_header Cache-Control "public"; | 重複訪問零流量 |
| Gzip/ Brotli 壓縮 | 預先壓縮 .html.gz/.html.br,Nginx gzip_static on; | 傳輸體積減少 70% |
| 增量部署 | rsync 同步變更檔案至多台前端伺服器 | 部署秒級、零停機 |
| 搜尋引擎友善 | 生成 JSON-LD 結構化資料、Sitemap、canonical 標籤 | SEO 排名提升 |
flock() 或 Redis 分散式鎖保護單檔生成dir_index、考慮合併小檔或使用對象儲存若專案為內容導向(部落格、文件、行銷頁),考慮 Hugo、Next.js (export)、Astro、VitePress 等現代 SSG,提供:
PHP 靜態化發布系統仍適合「既有 PHP CMS 改造」或「需深度整合 PHP 業務邏輯」的場景,新專案優先評估現代 SSG。