萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET URL 重寫與偽靜態完整實作:Microsoft URLRewriter、IIS 通配符映射、Rewrite 模組

URL 重寫 (URL Rewriting) 能將友善靜態化 URL (如 `/article/123.html`) 內部映射至動態頁面 (`/Article.aspx?id=123`),提升 SEO、隱藏技術細節、便於遷移。本文涵蓋 **Microsoft URLRewriter (舊專案)**、**IIS 7+ URL Rewrite Module (現代標準)**、**ASP.NET Core Middleware** 三種方案的完整配置與避坑指南。

方案一:Microsoft URLRewriter (僅 .NET Framework / IIS 6/7 傳統模式)

1. 取得組件

下載 `Microsoft.Web.UrlRewriter.dll` (或原始碼專案編譯),加入專案參考。

2. web.config 配置

<configuration>
  <configSections>
    <section name="RewriterConfig" type="URLRewriter.Config.RewriterConfigSerializerSectionHandler, URLRewriter" />
  </configSections>

  <RewriterConfig>
    <Rules>
      <RewriterRule>
        <LookFor>~/article/(\d+)\.html</LookFor>
        <SendTo>~/Article.aspx?id=$1</SendTo>
      </RewriterRule>
      <RewriterRule>
        <LookFor>~/category/([\w-]+)/?$</LookFor>
        <SendTo>~/Category.aspx?name=$1</SendTo>
      </RewriterRule>
    </Rules>
  </RewriterConfig>

  <system.web>
    <httpHandlers>
      <add verb="*" path="*.aspx" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
      <add verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" />
    </httpHandlers>
  </system.web>

  <system.webServer> <!-- IIS 7+ Integrated -->
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRewriter" type="URLRewriter.RewriterModule, URLRewriter" />
    </modules>
    <handlers>
      <add name="HtmlRewriter" verb="*" path="*.html" type="URLRewriter.RewriterFactoryHandler, URLRewriter" preCondition="integratedMode" />
    </handlers>
  </system.webServer>
</configuration>

3. IIS 6 / 傳統模式 必做:通配符應用程式映射

IIS 管理員 → 網站/虛擬目錄 → **配置** → **通配符應用程式對應** → 執行檔:`C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll`,**取消勾選「確認檔案是否存在」**。這讓 `.html` 請求也進入 ASP.NET 管線由 Rewriter 處理。

方案二:IIS URL Rewrite Module 2.0 (IIS 7+ 推薦、效能最佳)

  1. 安裝 URL Rewrite Module (伺服器級)。
  2. `web.config` `` 區段配置:
<rewrite>
  <rules>
    <rule name="ArticleHtml" stopProcessing="true">
      <match url="^article/(\d+)\.html$" />
      <action type="Rewrite" url="Article.aspx?id={R:1}" appendQueryString="true" />
    </rule>
    <rule name="CategorySeo" stopProcessing="true">
      <match url="^category/([\w-]+)/?$" />
      <action type="Rewrite" url="Category.aspx?name={R:1}" />
    </rule>
    <!-- 反向輸出重寫 (Response Filter) 讓頁面輸出的連結自動變靜態化 -->
    <outboundRules>
      <rule name="OutboundArticle" preCondition="IsHtml">
        <match filterByTags="A" pattern="Article\.aspx\?id=(\d+)" />
        <action type="Rewrite" value="article/{R:1}.html" />
      </rule>
      <preConditions>
        <preCondition name="IsHtml">
          <add input="{RESPONSE_CONTENT_TYPE}" pattern="text/html" />
        </preCondition>
      </preConditions>
    </outboundRules>
  </rules>
</rewrite>

**優點**:原生 C++ 模組、效能極高、支援出站重寫 (自動轉換頁面連結)、正則功能豐富、GUI 管理介面。

方案三:ASP.NET Core URL Rewriting Middleware

// Program.cs / Startup.cs
app.UseRewriter(new RewriteOptions()
    .AddRewrite(@"^article/(\d+)\.html$", "Article/$1", skipRemainingRules: true)
    .AddRewrite(@"^category/([\w-]+)/?$", "Category/$1", skipRemainingRules: true)
    .AddRedirect(@"^old-page\.aspx$", "new-page", 301)); // 永久重導向

// 或使用 MapWhen 精確控制
app.MapWhen(ctx => ctx.Request.Path.StartsWithSegments("/legacy"), appBuilder => {
    appBuilder.UseRewriter(new RewriteOptions().AddRewrite(...));
});

偽靜態 vs 真靜態 vs 靜態化

模式原理優點缺點
URL 重寫 (偽靜態)動態頁面 + 重寫規則即時資料、無生成延遲、部署簡單每請求執行動態邏輯、資料庫壓力大
靜態化 (生成 .html)定時/觸發生成實體靜態檔極速、零資料庫壓力、抗高併發資料非即時、部署複雜、龐大檔案管理
真靜態 (CDN/SSG)建置時期生成 (Next.js, Astro, Hugo)極致效能、安全、邊緣緩存動態互動需客戶端 JS / API

常見問題排查

  • 404 Not Found:未安裝 Rewrite Module / 未啟用 `runAllManagedModulesForAllRequests` / `path` 模式不匹配。
  • 無限循環:規則互相觸發,加 `stopProcessing="true"`、避免 `Rewrite` 產生的 URL 又匹配其他規則。
  • CSS/JS/圖片 404:相對路徑基於重寫後 URL 解析,改用絕對路徑 `/Content/...` 或 ``。
  • Postback 表單 Action 錯誤:WebForms `
    ` 會輸出重寫前 URL,需在 `Page_Load` 修正:`form1.Action = Request.RawUrl;`。

選擇 **IIS URL Rewrite Module** 為首選 (效能、功能、維護最佳);舊專案受限於 IIS 6/傳統模式才用 Microsoft URLRewriter;新專案直接用 Core Middleware 或前端框架路由。

copyright © 萬盛學電腦網 all rights reserved