偽靜態 (URL Rewriting) 將動態網址 (`.aspx?id=1`) 重寫為靜態化路徑 (`.html`、目錄式),有利 SEO、使用者體驗與安全性。本文針對 ASP.NET Web Forms (`.aspx`) 使用經典 UrlRewriter.NET (或 `Intelligencia.UrlRewriter`) 在 `Web.config` 中設定規則,含單一頁面、單參數、多參數、正則捕獲群組對應完整範例。
# NuGet 套件管理器主控台
Install-Package UrlRewriter.NET
或手動將 `Intelligencia.UrlRewriter.dll` 放入 `bin` 目錄,並在 `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);
}
若需在頁面輸出的超連結自動轉為靜態化網址,需搭配 `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,支援雙向 (輸入重寫 + 輸出產生) 且效能更好。