URL 重寫通過 Apache mod_rewrite 模組,將用戶友好的靜態風格 URL (如 /article/123.html) 內部轉發為動態腳本參數 (如 index.php?id=123),實現 SEO 優化、隱藏技術細節、統一入口。
編輯 httpd.conf,取消註釋:
LoadModule rewrite_module modules/mod_rewrite.so
找到網站根目錄對應的 <Directory> 區塊,修改:
<Directory "D:/wwwroot">
Options FollowSymLinks ExecCGI Indexes
AllowOverride All # 關鍵:從 None 改為 All
Require all granted
</Directory>
# Windows
httpd -k restart
# Linux systemd
systemctl restart httpd / apache2
於項目根目錄建立 .htaccess (Windows 下新建文本文件另存為 .htaccess):
<IfModule mod_rewrite.c>
RewriteEngine On
# 規則範例:/action-123.html → index.php?action=action&id=123
RewriteRule ^([a-zA-Z]+)-([0-9]+)\.html$ index.php?action=$1&id=$2 [L,QSA]
# 常用規則模板
# 1. 統一入口 (前端控制器模式)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA]
# 2. 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 3. 統一 www / 非 www
RewriteCond %{HTTP_HOST} ^example\.com [NC]
RewriteRule ^(.*)$ https://www.example.com/$1 [L,R=301]
# 4. 防盜鏈
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|png|gif|webp)$ - [F,NC]
</IfModule>
| 符號 | 含義 |
|---|---|
^ | 字串開頭 |
$ | 字串結尾 |
() | 捕獲組,對應 $1, $2...$9 |
[a-zA-Z] | 字母範圍 |
[0-9] | 數字範圍 |
+ | 前一字符出現 1 次或多次 |
* | 前一字符出現 0 次或多次 |
. | 任意字符 (需轉義 \.) |
[L] | Last:匹配後停止後續規則 |
[QSA] | Query String Append:保留原查詢字串 |
[R=301] | 永久重定向 (瀏覽器地址欄變化) |
[F] | Forbidden:返回 403 |
[NC] | No Case:不區分大小寫 |
<?php
// index.php
$action = $_GET['action'] ?? 'default';
$id = (int)($_GET['id'] ?? 0);
echo "Action: {$action}, ID: {$id}";
瀏覽器訪問:https://yourdomain.com/list-42.html
預期輸出:Action: list, ID: 42
AllowOverride None 未改為 All → .htaccess 不生效RewriteLog 除錯 (Apache 2.4+ 用 LogLevel alert rewrite:trace3)RewriteCond %{REQUEST_FILENAME} !-f 排除實體文件