在虛擬主機或無法取得 IIS 管理權限的環境下,若想實現類似靜態頁面的 URL 存取方式(例如用 12345.html 取代 show.aspx?id=12345,或像百度空間般用 https://hi.jb51.net/wu1987116 取代 https://hi.jb51.net/index.aspx?UserName=wu1987116),透過 URLRewriter.dll 是一個經典且輕量的解決方案。本文將詳細說明如何在不修改 IIS 設定的前提下,完成 URL 重寫的部署與規則配置。
bin 目錄下找到 URLRewriter.dll,複製到你的 Web 專案 bin 資料夾並加入參考。在 <configuration> 根節點直下、<system.web> 之前加入:
<configSections>
<section name="RewriterConfig"
type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
</configSections>
此設定指定 RewriterConfig 區段由 URLRewriter.Config.RewriterConfigSerializerSectionHandler 處理,該類別位於 URLRewriter.dll 中。
在 <system.web> 下的 <httpHandlers> 加入(順序很重要):
<httpHandlers>
<add verb="*" path="*.html"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
<add verb="*" path="*"
type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
</httpHandlers>
說明: 先攔截 .html,再攔截所有路徑(含無副檔名)。若順序顛倒,path="*" 會搶先處理導致 .html 規則失效。
同樣放在 <configuration> 直下:
<RewriterConfig>
<Rules>
<RewriterRule>
<LookFor>~/(.+).html</LookFor>
<SendTo>~/Shownews.aspx?ShowID=$1</SendTo>
</RewriterRule>
<RewriterRule>
<LookFor>~/(.+)</LookFor>
<SendTo>~/blog.aspx?UserName=$1</SendTo>
</RewriterRule>
</Rules>
</RewriterConfig>
LookFor:使用正則表達式比對傳入 URL,括號內為捕獲群組。SendTo:目標實際路徑,$1、$2… 對應第 1、2… 個捕獲群組。.html)必須置於通用規則之前。<RewriterRule>
<LookFor>~/(.*)/TestUrlRe/file(.*)/(.*)\.html</LookFor>
<SendTo>~/WebForm1.aspx?id=$2&type=$3</SendTo>
</RewriterRule>
在 .aspx 頁面中動態產出偽靜態連結:
<a href="news_<%=newsid%>.html" target="_blank">新聞標題</a>
正式環境若發現重寫不生效,通常是因為 IIS 沒有將所有請求管線導向 ASP.NET。需在 IIS → 網站屬性 → 主目錄 → 配置 → 通配符應用程式對應,新增 aspnet_isapi.dll 並**取消勾選「確認檔案是否存在」**。
透過 URLRewriter.dll 僅修改 Web.config 與前端連結,即可在無 IIS 權限環境下實現靈活的 URL 重寫,支援任意副檔名與無副檔名路由,是早期 ASP.NET WebForms 專案常用的偽靜態方案。