Apache mod_rewrite 在主配置 httpd.conf 與分散式配置 .htaccess 中的 匹配基準路徑不同,導致同一規則在兩處表現不一,是常見遷移錯誤來源。
| 配置位置 | 匹配字串基準 | 範例規則 |
|---|---|---|
httpd.conf (VirtualHost/Directory) | 完整 URL 路徑,**含開頭斜線** | RewriteRule ^/(w+)/list(d+).html /Article/ArticleList.aspx?ArticleType=$1&Page=$2 |
.htaccess | 相對於 .htaccess 所在目錄的路徑,**不含開頭斜線** | RewriteRule ^(w+)/list(d+).html /Article/ArticleList.aspx?ArticleType=$1&Page=$2 |
假設網站根目錄 /var/www/html,.htaccess 放於根目錄,請求 /news/list5.html:
/news/list5.html → 模式需以 ^/ 開頭。news/list5.html(已剝離前導斜線) → 模式 不可 以 ^/ 開頭。httpd.conf 移至 .htaccess 時,**移除模式開頭的 ^/** 或改為 ^。.htaccess 置於子目錄(如 /var/www/html/blog/.htaccess),匹配基準進一步去除 blog/ 前綴。RewriteBase 指令可手動設定基準路徑,簡化規則撰寫。RewriteLog (Apache 2.4 用 LogLevel alert rewrite:trace3) 觀察實際匹配字串除錯。.htaccess。AllowOverride None 禁用 .htaccess,提升效能與安全性。理解路徑基準差異,是 Apache Rewrite 規則跨環境無縫遷移的關鍵。