URL Rewrite 需要 Web 伺服器支援。Apache 需載入 mod_rewrite 模組,IIS 則需安裝 URL Rewrite Module。本文以 Apache 為主說明。
httpd.conf(或 apache2.conf)。#LoadModule rewrite_module modules/mod_rewrite.so,移除前面的 #。AllowOverride 設為 All(或至少包含 FileInfo),允許 .htaccess 覆寫規則。systemctl restart httpd 或 apachectl -k restart。<IfModule mod_rewrite.c>
RewriteEngine On
# 範例:將 index-123.html 重寫為 index.php?__rewrite_arg=123
RewriteRule ^(.*?(?:index|dispbbs))-([-0-9]+)\.html$ $1.php?__is_apache_rewrite=1&__rewrite_arg=$2 [L]
# 進階:ASP 舊網址映射到 PHP(保留查詢字串,轉小寫)
RewriteMap tolowercase int:tolower
RewriteCond %{QUERY_STRING} (?:boardid|page|id|replyid|star|skin)=\d+ [NC]
RewriteRule ^(.*(?:index|dispbbs))\.asp$ $1.php?${tolowercase:%{QUERY_STRING}}&__is_apache_rewrite=1 [L]
</IfModule>
將上述 <IfModule> 區塊內容直接放入網站根目錄的 .htaccess,無需重啟 Apache 即時生效。
| 旗標 | 含義 |
|---|---|
[L] | Last:停止後續規則處理 |
[R=301] | 永久重導向(瀏覽器網址列會變) |
[NC] | No Case:大小寫不敏感 |
[QSA] | Query String Append:保留原查詢字串 |
[PT] | Pass Through:交給後續處理器(如 mod_alias) |
# 將 /article/123.html 映射到 /article.php?id=123
RewriteRule ^article/([0-9]+)\.html$ article.php?id=$1 [L,QSA]
# 強制 HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# 防盜鏈
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com [NC]
RewriteRule \.(jpg|png|gif)$ - [F,NC]
LogLevel alert rewrite:trace3,查看 error.log 追蹤匹配過程。RewriteLog 與 RewriteLogLevel(Apache 2.2 舊版)。IIS 使用 web.config 定義規則,語法採 XML 格式:
<rule name="Rewrite to PHP" stopProcessing="true">
<match url="^article/([0-9]+)\.html$" />
<action type="Rewrite" url="article.php?id={R:1}" appendQueryString="true" />
</rule>
掌握 RewriteCond、RewriteRule、正則表達式與旗標組合,即可靈活實現 URL 美化、舊網址遷移、安全防護等需求。建議優先在 .htaccess 開發測試,上線後遷移至主配置以提升效能。