Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> 電腦軟體教學 >> 伺服器技術 >> 關於伺服器

Apache 與 IIS 偽靜態 (URL Rewrite) 規則語法差異完整對比

編輯:關於伺服器

核心差異速查表

項目Apache (mod_rewrite)IIS (URL Rewrite Module / ISAPI Rewrite)
配置位置.htaccess / httpd.conf / vhost.confweb.config (system.webServer/rewrite)
引擎啟用RewriteEngine On預設啟用 (安裝模組後)
規則指令RewriteRule (XML 結構)
條件判斷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`

Apache (.htaccess / vhost)

RewriteEngine On
RewriteRule ^product-([0-9]+)\.html$ product.php?id=$1 [L,NC,QSA]

IIS (web.config)

<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>

進階:多條件、重導向、代理

Apache:強制 HTTPS + www 統一

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]

IIS:同功能

<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>

常見陷阱與避坑指南

問題ApacheIIS
規則不生效檢查 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: `RewriteLog` (舊版) / `LogLevel alert rewrite:trace3` (2.4+) 除錯。
  • IIS: 失敗要求追蹤 (Failed Request Tracing) + `web.config` 內 `` 區段;URL Rewrite Module 官網 含測試工具。
  • 線上轉換: 部分規則可用工具互轉,但複雜邏輯建議手寫。

總結

Apache `mod_rewrite` 與 IIS `URL Rewrite` **功能對等、語法迥異**。Apache 採指令式、正則優先;IIS 採 XML 宣告式、結構化條件。遷移專案時,**逐條對照轉寫**,並用追蹤日誌驗證,是唯一可靠路徑。

Copyright © Windows教程網 All Rights Reserved