本文與前一篇 (ID 67457) 內容高度重複,均為使用 URLRewriter.dll 實現無需 IIS 設定的 URL 重寫。此處補充更多實務細節與常見問題排查。
URLRewriter.dll。Web.config 註冊 <configSections>、<httpHandlers>、<RewriterConfig> 三區塊。news_123.html)。| 現象 | 原因 | 對策 |
|---|---|---|
| 重寫不生效、直接 404 | IIS 未將 .html 對應至 ASP.NET | 加入萬用字元對應至 aspnet_isapi.dll 並取消「驗證檔案存在」 |
| 規則順序錯誤導致錯誤對應 | path="*" 在 path="*.html" 之前 | 調整 <httpHandlers> 順序,特定副檔名優先 |
| CSS/JS/圖片 404 | 靜態資源也被重寫規則攔截 | 規則加入排除:<LookFor>~/(?!.*\.(css|js|png|jpg|gif)).+\.html</LookFor> |
| PostBack 後網址變回 .aspx | Form action 未重寫 | 使用 form.Action = Request.RawUrl 或 Control Adapter 修正 |
<RewriterConfig>
<Rules>
<!-- 產品頁 -->
<RewriterRule>
<LookFor>~/product/(\d+)/(\w+)\.html</LookFor>
<SendTo>~/ProductDetail.aspx?Id=$1&Category=$2</SendTo>
</RewriterRule>
<!-- 使用者個人頁 -->
<RewriterRule>
<LookFor>~/user/([\w-]+)</LookFor>
<SendTo>~/Profile.aspx?Name=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
web.config <system.webServer>/<rewrite>,效能更高且不影響 ASP.NET 管線。