頁面靜態化是優化 Web 應用響應速度、降低服務器負載的核心手段之一。本文系統梳理動態頁面靜態化的三大主流方案:URL 偽靜態、輸出緩衝生成純靜態、定時/觸發式更新策略,並提供 Apache/Nginx 重寫配置示例。
通過 Web 服務器重寫模塊將動態 URL 映射為靜態化路徑,實際仍由 PHP 處理。
示例: index.php?c=play&id=1111 → /play/1111.html
Apache 配置(.htaccess 或 httpd-vhosts.conf):
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^play/([0-9]+)\.html$ index.php?c=play&id=$1 [L]
利用 PHP ob_start() 捕獲輸出,配合 file_put_contents() 寫入磁盤。
ob_start():開啟輸出緩衝ob_get_contents():獲取緩衝區內容ob_clean() / ob_get_clean():清空/獲取並清空緩衝區file_put_contents($file, $content):原子寫入文件crontab 定時運行生成腳本*/5 * * * * /usr/bin/php /var/www/html/generate_static.php
<?php
$cache_file = 'index.html';
$expire = 300; // 5分鐘
if (file_exists($cache_file) && (time() - filemtime($cache_file) < $expire)) {
require_once $cache_file;
exit;
}
ob_start();
// 連接數據庫、獲取數據、渲染模板
echo 'Hello Static World!';
file_put_contents($cache_file, ob_get_contents());
ob_end_flush();
?>
高流量站點常採用:首頁/列表頁純靜態 + 詳情頁偽靜態 + 緩存層 的混合架構。
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
根據業務場景選擇方案:內容更新頻率低、訪問量大 → 純靜態;需實時權限、個性化 → 偽靜態 + 緩存;兩者結合往往能達到最佳性價比。