首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET URL Rewrite 實戰教學:HttpModule 攔截 + 正則比對 + IIS 擴展對應

     編輯:關於ASP.NET

URL 重寫是 SEO 友善、使用者體驗、安全性隱藏技術細節的關鍵技術。本文以實作專案為例,示範如何使用微軟 `URLRewriter.dll` 搭配自訂 `HttpModule`,達成「任意 URL 重寫至 `.aspx` 帶參數頁面」的完整流程,含正則比對邏輯、Web.config 註冊、IIS 副檔名對應設定。

需求場景

使用者瀏覽:https://song2.cn/viewnews/2009/3/2.html
實際重寫:https://song2.cn/viewnews.aspx?id=2&year=2009&month=3

支援多筆規則、正則擷取群組參數 (`$1`, `$2`...)、預設導向錯誤頁。

實作步驟

1. 取得組件

下載 `URLRewriter.dll` (微軟官方 / CodePlex 歷史版本),加入專案參考。

2. 建立自訂 HttpModule (類別庫專案)

using System;
using System.Web;
using URLRewriter;

namespace URL
{
    public class MyRewriter : BaseModuleRewriter
    {
        protected override void Rewrite(string requestedPath, HttpApplication app)
        {
            // 正則比對範例
            if (System.Text.RegularExpressions.Regex.IsMatch(requestedPath, 
                @"viewnews/(\d{4})/(\d{1,2})/(\d{1,2})\.html"))
            {
                var match = System.Text.RegularExpressions.Regex.Match(requestedPath,
                    @"viewnews/(\d{4})/(\d{1,2})/(\d{1,2})\.html");
                string id = match.Groups[3].Value;
                string year = match.Groups[1].Value;
                string month = match.Groups[2].Value;
                app.Context.RewritePath($"/viewnews.aspx?id={id}&year={year}&month={month}");
            }
            else
            {
                app.Context.RewritePath("/here.aspx"); // 預設/錯誤頁
            }
        }
    }
}

3. Web.config 註冊 HttpModule

<configuration>
  <system.web>
    <httpModules>
      <add type="URL.MyRewriter" name="URLRewriter" />
    </httpModules>
    <compilation debug="true" />
    <authentication mode="Windows" />
  </system.web>
</configuration>

IIS 7+ 整合模式** 需改註冊至 ``:

<system.webServer>
  <modules>
    <add name="URLRewriter" type="URL.MyRewriter" />
  </modules>
</system.webServer>

4. 關鍵:IIS 設定 `.html` 對應 ASP.NET ISAPI

預設 IIS 不會將 `.html` 請求交給 ASP.NET 處理,必須手動對應:

  1. IIS 管理員 → 網站 → 右鍵「屬性」 → 「主目錄」 → 「配置」
  2. 「應用程式副檔名對應」列表找 `.aspx` → 「編輯」 → 複製「可執行檔」路徑
    (例:`C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll`)
  3. 「新增」→ 可執行檔貼上上述路徑 → 副檔名填 `.html` → 取消勾選「確認檔案存在」 → 確定

如此 `.html` 請求才會進入 ASP.NET 管線,觸發 `HttpModule` 重寫邏輯。

進階模式:Web.config 宣告式規則 (無需自訂類別)

`URLRewriter` 內建支援組態檔規則定義:

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

<RewriterConfig>
  <Rules>
    <RewriterRule>
      <LookFor>~/Sell/(\d+)\.html</LookFor>
      <SendTo>~/Search/Search_Sell.aspx?id=$1</SendTo>
    </RewriterRule>
    <RewriterRule>
      <LookFor>~/Buy/(\d+)\.html</LookFor>
      <SendTo>~/Search/Search_Buy.aspx?id=$1</SendTo>
    </RewriterRule>
  </Rules>
</RewriterConfig>

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

常見坑點與解決

問題原因解決
.html 不重寫IIS 未對應 .html 至 aspnet_isapi.dll完成步驟 4 設定
規則不生效正則寫錯 / LookFor 路徑格式不符 (含/不含 ~)用 Regex Tester 驗證、記錄 requestedPath 除錯
無限重導向RewritePath 目標又符合 LookFor 條件目標用 .aspx、或加排除條件
PostBack 後網址變回 .aspx表單 action 為原始 .aspx 路徑用 Control Adapter 覆寫 Form Action、或 JavaScript 修正
IIS 7+ 模組不載入註冊在 system.web 而非 system.webServer移至 `` 區段、設定 `preCondition="integratedMode"`

現代化替代方案

  • ASP.NET Core:`app.UseRewriter()` + `RewriteOptions` / `MapWhen` / 中介軟體
  • IIS URL Rewrite Module 2.0+:原生效能最佳、支援輸出重寫、規則匯入匯出、GUI 管理
  • ASP.NET 4.5+ Routing** (`System.Web.Routing`):`RouteCollection.MapPageRoute`、WebForms 路由
  • 反向 Proxy (Nginx/ARR)**:在網關層統一重寫,應用程式零感知

URL Rewrite 是「不變更後端邏輯,改善前端呈現」的經典技術。無論用 HttpModule、Routing、IIS 模組或網關,核心都是**將外部可見 URL 映射至內部處理端點**,掌握攔截點、比對邏輯、參數傳遞、副檔名對應這四大關鍵,即可在任何 ASP.NET 版本中遊刃有餘。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved