偽靜態技術能將動態 URL(如 index.php?action=page&id=18)轉換為靜態風格 URL(如 page-18.html),有利於 SEO、使用者記憶與分享。本文詳述 Apache mod_rewrite 模組的啟用、.htaccess 設定、重寫規則撰寫與 PHP 配合處理的完整流程。
# 1. 檢查是否已載入
php -i | grep "Loaded Modules" # 或建立 phpinfo() 頁面搜尋 "mod_rewrite"
# 2. 若未啟用,編輯 httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so # 移除行首 # 號
# 3. 重啟 Apache
sudo systemctl restart httpd # 或 apachectl restart
在 httpd.conf 中找到網站根目錄對應的 <Directory> 區塊,修改 AllowOverride:
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride All # 原為 None,改為 All 允許 .htaccess 生效
</Directory>
於網站根目錄建立 .htaccess(注意檔名以點開頭):
RewriteEngine On
# 規則 1:單一數字 ID → index.php?id=數字
RewriteRule ^([0-9]+)$ index.php?id=$1 [L]
# 規則 2:動作-編號.html → index.php?action=動作&id=編號
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]
# 旗標說明:
# L (Last) : 停止後續規則處理
# QSA (QueryStringAppend) : 保留原查詢字串(如 ?foo=bar)並合併
<?php
// index.php
$action = $_GET['action'] ?? 'default';
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
echo "Action: {$action}
";
echo "ID: {$id}";
// 實際應用中可根據 action 分派控制器
switch ($action) {
case 'page': showPage($id); break;
case 'article': showArticle($id); break;
default: showHome(); break;
}
?>
| 需求 | RewriteRule | 說明 |
|---|---|---|
| 文章頁:/article/123.html | ^article/([0-9]+)\.html$ | 固定前綴 + 數字 ID |
| 分頁:/list-2.html | ^list-([0-9]+)\.html$ | 對應 list.php?page=2 |
| 多參數:/product/cat-5/brand-3.html | ^product/cat-([0-9]+)/brand-([0-9]+)\.html$ | $1=分類ID, $2=品牌ID |
| 中文標題:/post/標題-slug-456.html | ^post/([^/]+)-([0-9]+)\.html$ | [^/]+ 匹配非斜線字元(含中文) |
.htaccess 語法錯誤、AllowOverride 未設為 All、規則無限循環(善用 RewriteCond 排除實體檔案)。RewriteEngine On、檔案權限正確(644)、Apache 已重啟。/article/123.html),導致相對路徑錯誤。解決:使用絕對路徑 /css/style.css 或 <base href="/">。RewriteLog "/var/log/apache2/rewrite.log" RewriteLogLevel 3(Apache 2.4+ 改用 LogLevel alert rewrite:trace3)。若使用 Nginx,無 .htaccess,需在 server 區塊直接撰寫:
location / {
try_files $uri $uri/ /index.php?$query_string;
# 或具體規則:
rewrite ^/([a-zA-Z]+)-([0-9]+)\.html$ /index.php?action=$1&id=$2 last;
}
掌握 mod_rewrite 正則規則與旗標運用,是 PHP 開發者實現優雅 URL 的核心技能。建立規則時遵循「由具體到一般」順序,善用 RewriteCond 排除實體資源,並搭配 PHP 路由機制,即可構建整潔、SEO 友善的 URL 架構。