| 項目 | Apache (mod_rewrite) | IIS (URL Rewrite Module / ISAPI Rewrite) |
|---|---|---|
| 配置位置 | .htaccess / httpd.conf / vhost.conf | web.config (system.webServer/rewrite) |
| 引擎啟用 | RewriteEngine On | 預設啟用 (安裝模組後) |
| 規則指令 | RewriteRule | |
| 條件判斷 | RewriteCond | |
| 正則引擎 | PCRE (Perl 相容) | ECMAScript / .NET Regex (略有差異) |
| 反向引用 | $1, $2... (RewriteRule), %1, %2... (RewriteCond) | {R:1}, {R:2}... (Rule), {C:1}... (Condition) |
| 旗標/選項 | [L, R=301, NC, QSA, PT...] | stopProcessing, redirectType, ignoreCase, appendQueryString |
| 變數取得 | %{HTTP_HOST}, %{REQUEST_URI}, %{QUERY_STRING} | {HTTP_HOST}, {REQUEST_URI}, {QUERY_STRING} |
目標:將 `/product.php?id=123` 重寫為 `/product-123.html`
RewriteEngine On RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1 [L,NC,QSA]
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="ProductRewrite" stopProcessing="true">
<match url="^product-([0-9]+)\.html$" ignoreCase="true" />
<action type="Rewrite" url="product.php?id={R:1}" appendQueryString="true" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>
RewriteEngine On
# HTTP → HTTPS
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# non-www → www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
<rule name="ForceHTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
<rule name="ForceWWW" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\." negate="true" />
</conditions>
<action type="Redirect" url="https://www.{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
| 問題 | Apache | IIS |
|---|---|---|
| 規則不生效 | 檢查 AllowOverride All、mod_rewrite 載入、.htaccess 權限 | 檢查 URL Rewrite Module 安裝、web.config 位置 (網站根目錄)、IIS 重啟 |
| 無限迴圈 | 缺少 [L] 或條件未排除重寫後 URL | 缺少 stopProcessing="true"、match pattern 匹配到重寫後 URL |
| 查詢字串丟失 | 加 [QSA] 旗標 | action appendQueryString="true" |
| 大小寫敏感 | 加 [NC] 旗標 | match ignoreCase="true" / condition ignoreCase="true" |
| 效能差 | 避免過多 RewriteCond、用 ^$ 錨定、快取編譯結果 | 避免複雜 condition、用 stopProcessing、輸出快取 |
Apache `mod_rewrite` 與 IIS `URL Rewrite` **功能對等、語法迥異**。Apache 採指令式、正則優先;IIS 採 XML 宣告式、結構化條件。遷移專案時,**逐條對照轉寫**,並用追蹤日誌驗證,是唯一可靠路徑。