偽靜態 (URL Rewriting) 將動態 URL (如 index.php?action=page&id=18) 重寫為靜態風格 (如 page-18.html),利於 SEO、使用者體驗與安全性 (隱藏參數結構)。
# httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so
# 移除前面的 # 號,重啟 Apache
驗證:phpinfo() → Loaded Modules 應包含 mod_rewrite。
# httpd.conf
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride All # 原為 None,改為 All
</Directory>
# .htaccess
RewriteEngine On
# 範例 1: 簡單數字 ID
RewriteRule ^([0-9]+)$ index.php?id=$1 [L]
# 範例 2: 偽靜態 HTML (action-id.html)
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L]
# 範例 3: 通用 MVC 路由 (所有非實體檔案導向 index.php)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
| 符號 | 含義 |
|---|---|
| ^ | 字串開頭 |
| $ | 字串結尾 |
| (...) | 捕獲群組,對應 $1, $2... |
| [a-zA-Z] | 字母範圍 |
| [0-9] | 數字範圍 |
| {1,} | 至少 1 次 (等同 +) |
| [L] | Last,停止後續規則 |
| [QSA] | Query String Append,保留原查詢字串 |
<?php
// index.php
echo 'Action: ' . ($_GET['action'] ?? 'none') . '<br>';
echo 'ID: ' . ($_GET['id'] ?? 'none') . '<br>';
httpd-vhosts.conf 新增 VirtualHost,指定 DocumentRoot 與 ServerName。C:\Windows\System32\drivers\etc\hosts 加入 127.0.0.1 myproject.local。https://myproject.local/page-18.html 即可測試。RewriteCond %{REQUEST_FILENAME} !-f 排除實體檔案。