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

ASP.NET URL Rewriter 實現任意二級域名:HttpModule 攔截重寫完整教學

     編輯:關於ASP.NET

核心概念:URL 重寫發生在伺服器端

瀏覽器網址列**不會改變**。使用者輸入 `https://user.example.com`,DNS 解析至同一台 Web Server,IIS 接收請求,ASP.NET `HttpModule` 在管線早期攔截,**內部**將路徑重寫為 `https://example.com/User.aspx?username=user`,後續處理完全基於重寫後的路徑。使用者感知不到任何轉向。

實作三步驟

1. 制定重寫規則

例:`{subdomain}.example.com` → `/User/Profile.aspx?domain={subdomain}`

2. 撰寫 HttpModule

using System;
using System.Web;

public class SubdomainRewriter : IHttpModule
{
    public void Init(HttpApplication context)
    {
        context.BeginRequest += OnBeginRequest;
    }

    private void OnBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = (HttpApplication)sender;
        HttpContext context = app.Context;

        string host = context.Request.Url.Host.ToLower(); // 如: user.example.com
        string[] parts = host.Split('.');

        // 判斷是否為二級域名 (排除 www、本機、IP)
        if (parts.Length == 3 && parts[1] == "example" && parts[2] == "com" && parts[0] != "www")
        {
            string subdomain = parts[0]; // user
            string rewritePath = $"/User/Profile.aspx?domain={subdomain}";

            // 內部重寫:瀏覽器網址不變
            context.RewritePath(rewritePath);
        }
    }

    public void Dispose() { }
}

3. 註冊 HttpModule (web.config)

IIS 6 / 傳統管線模式:

<system.web>
  <httpModules>
    <add name="SubdomainRewriter" type="MyNamespace.SubdomainRewriter, MyAssembly" />
  </httpModules>
</system.web>

IIS 7+ / 整合管線模式 (建議):

<system.webServer>
  <modules>
    <add name="SubdomainRewriter" type="MyNamespace.SubdomainRewriter, MyAssembly" preCondition="managedHandler" />
  </modules>
</system.webServer>

進階:使用成熟的 URL Rewriter 套件

手寫 HttpModule 適合簡單規則。複雜專案建議使用:

  • URL Rewrite Module (IIS 原生):`web.config` 內 `` 宣告式規則,支援正則、條件、對應表、輸出重寫,效能最佳 (原生 C++ 模組)。
  • UrlRewriter.NET / UrlRewritingNet.UrlRewriter:經典 .NET 套件,XML 設定規則,支援 `` 區段。
  • ASP.NET Core Endpoint Routing / RewriteMiddleware:現代專案使用 `app.UseRewriter()`。

IIS URL Rewrite 範例 (web.config)

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Subdomain to User Profile" stopProcessing="true">
        <match url="^(.*)$" />
        <conditions>
          <add input="{HTTP_HOST}" pattern="^([^.]+)\.example\.com$" />
          <add input="{C:1}" pattern="^www$" negate="true" />
        </conditions>
        <action type="Rewrite" url="/User/Profile.aspx?domain={C:1}" appendQueryString="true" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

關鍵注意事項

  1. DNS 設定**:需設定泛域名 `*.example.com` A 記錄指向 Web Server IP。
  2. IIS 繫結**:網站繫結需包含 `example.com` 與 `*.example.com` (或不指定主機名稱)。
  3. 相對路徑問題**:重寫後頁面中的相對路徑 (CSS/JS/圖片) 可能失效。解決:使用根路徑 `/Content/...` 或 ``。
  4. 表單 PostBack**:重寫後表單 `action` 仍為原始二級域名 URL,PostBack 會再次觸發重寫,邏輯正常運作。
  5. Session/Cookie 域名**:若需跨二級域名共用 Session,設定 ``、``。

總結

任意二級域名實現核心:DNS 泛域名解析 + IIS 繫結 + ASP.NET 管線早期 `HttpModule`/`URL Rewrite Module` 內部重寫。採用 IIS 原生 URL Rewrite Module 為首選,效能最佳、規則聲明式、支援豐富條件與輸出重寫。手寫 HttpModule 適合輕量專案或特殊邏輯需求。

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