萬盛學電腦網

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

ASP.NET URL 重寫實現偽靜態:Web.config RewriterConfig 規則完整教學

前言

偽靜態 (URL Rewriting) 將動態網址 (`.aspx?id=1`) 重寫為靜態化路徑 (`.html`、目錄式),有利 SEO、使用者體驗與安全性。本文針對 ASP.NET Web Forms (`.aspx`) 使用經典 UrlRewriter.NET (或 `Intelligencia.UrlRewriter`) 在 `Web.config` 中設定規則,含單一頁面、單參數、多參數、正則捕獲群組對應完整範例。

一、安裝 UrlRewriter.NET

# NuGet 套件管理器主控台
Install-Package UrlRewriter.NET

或手動將 `Intelligencia.UrlRewriter.dll` 放入 `bin` 目錄,並在 `Web.config` 註冊模組。

二、Web.config 完整設定

<configuration>
  <configSections>
    <section name="rewriter" requirePermission="false" type="Intelligencia.UrlRewriter.Configuration.RewriterConfigurationSectionHandler, Intelligencia.UrlRewriter" />
  </configSections>

  <rewriter>
    <!-- 1. 首頁 -->
    <rewrite url="^~/index\.html$" to="~/Default.aspx" />

    <!-- 2. 產品列表:/products/c-12.html → /Products.aspx?cat=12 -->
    <rewrite url="^~/products/c-(\d+)\.html$" to="~/Products.aspx?cat=$1" />

    <!-- 3. 產品詳情:/product/123-slug.html → /Product.aspx?id=123 -->
    <rewrite url="^~/product/(\d+)-[^/]+\.html$" to="~/Product.aspx?id=$1" />

    <!-- 4. 多參數:/help/12_34.html → /Help.aspx?sid=12&cid=34 -->
    <rewrite url="^~/help/(\d+)_(\d+)\.html$" to="~/Help.aspx?sid=$1&cid=$2" />

    <!-- 5. 文章歸檔:/archive/2024/05.html → /Archive.aspx?y=2024&m=5 -->
    <rewrite url="^~/archive/(\d{4})/(\d{1,2})\.html$" to="~/Archive.aspx?y=$1&m=$2" />

    <!-- 6. 排除實體檔案 (css/js/圖片) 不重寫 -->
    <rewrite url="^~/assets/(.+)$" to="~/assets/$1" />
    <rewrite url="^~/scripts/(.+)$" to="~/scripts/$1" />
    <rewrite url="^~/styles/(.+)$" to="~/styles/$1" />
  </rewriter>

  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" />
    </modules>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
</configuration>

三、關鍵語法解析

符號意義
`^~/`錨定應用程式根目錄開頭 (避免匹配子目錄同名檔案)
`$`字串結尾
`(\d+)`捕獲群組:一或多位數字 → 對應 `$1`
`([^/]+)`捕獲非斜線字元 (slug)
`$1`, `$2`後向參照,對應第 1、2 個捕獲群組
XML 轉義 `&`,避免 Web.config 解析錯誤

四、程式碼端取得重寫後參數

重寫發生在 `BeginRequest` 階段,`Request.QueryString` 已自動包含重寫後的參數,程式碼無感知:

// Product.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
    string id = Request.QueryString["id"]; // 從 /product/123-slug.html 取得 "123"
    if (int.TryParse(id, out int pid))
        LoadProduct(pid);
}

五、進階:對應輸出 URL (Outbound Rewriting)

若需在頁面輸出的超連結自動轉為靜態化網址,需搭配 `Response.Filter` 或 ASP.NET 4.0+ `Response.RewritePath`,或改用 **ASP.NET Routing** (`MapPageRoute`) 同時處理輸入/輸出。

// Global.asax Application_Start
void RegisterRoutes(RouteCollection routes)
{
    routes.MapPageRoute("ProductDetail", "product/{id}-{slug}.html", "~/Product.aspx");
    routes.MapPageRoute("ProductList", "products/c-{cat}.html", "~/Products.aspx");
}

// 頁面產生連結
string url = RouteTable.Routes.GetVirtualPath(null, "ProductDetail", 
    new RouteValueDictionary { { "id", 123 }, { "slug", "product-name" } }).VirtualPath;
// 輸出:/product/123-product-name.html

建議:新專案直接使用 **ASP.NET Routing** (Web Forms 4.0+ 內建),取代 UrlRewriter,支援雙向 (輸入重寫 + 輸出產生) 且效能更好。

六、IIS 7+ 整合模式注意事項

  • `runAllManagedModulesForAllRequests="true"` 讓 Managed 模組處理靜態檔案請求 (會增加些許開銷),或改用 `` 搭配 `` 僅處理 Managed 請求。
  • 靜態檔案 (`.css`, `.js`, `.jpg`) 建議在 `` 中優先排除 (如範例規則 6),避免不必要的正則匹配。
  • 啟用失敗追蹤:`` 或 IIS 失敗請求追蹤 (FREB) 除錯重寫規則不生效。

七、SEO 與遷移建議

  1. 舊動態網址 301 重導向至新靜態網址:在 `Global.asax` `Application_BeginRequest` 檢查 `Request.RawUrl` 含 `?id=` 等舊參數則 `Response.RedirectPermanent(newUrl)`。
  2. 更新 `sitemap.xml`、內部連結、Canonical 標籤皆指向新靜態 URL。
  3. Google Search Console 提交新 Sitemap、監控收錄狀況。
copyright © 萬盛學電腦網 all rights reserved