在資源共享的前提下,首要目標是讓搜尋引擎能正確收錄頁面內容。避免濫用 AJAX 載入核心內容,僅在後台操作或用戶互動局部採用 AJAX。設計 HTML 時應遵循搜尋引擎收錄準則,善用語意化標籤。
涉及後端查詢優化、快取策略等,此處不贅述。
核心在於 Apache mod_rewrite、正則表達式與 Smarty 模板引擎的配合。熟練掌握正則是靈活實現偽靜態的關鍵。
在 httpd.conf 中啟用模組:LoadModule rewrite_module modules/mod_rewrite.so。若使用虛擬主機,可在 vhost 區塊加入重寫規則:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^xxx.com$
RewriteRule ^/([^\.\/]+)\.html$ /index.php?action=$1 [L]
說明: RewriteCond 設定條件(此處匹配主機名),RewriteRule 將類似 /action.html 的請求內部轉發至 /index.php?action=action。[L] 表示此規則為最後一條。
頁面中的連結需配合偽靜態格式(如 abc/action-doit.html)。手動修改連結既繁瑣又難以維護,建議使用 Smarty 的 register_outputfilter() 在輸出前自動轉換:
function change_url($tpl_output, &$smarty) {
$tpl_output = preg_replace('~\/index\.php\?action=([^&]+)~i', '/\\1.html', $tpl_output);
return $tpl_output;
}
$tpl->register_outputfilter('change_url');
同理可用 register_prefilter() 在模板編譯前處理。詳細用法請參閱 Smarty 手冊。