許多網站都會使用 URL 重寫功能,讓網址更簡潔、利於 SEO 且隱藏查詢字串參數。網路上雖有多種實作方式,但大多較為複雜難懂。本文介紹一個簡單易懂的方法:只需在 global.asax.cs 中加入 Application_BeginRequest 事件處理函式,即可輕鬆實現 URL 重寫。
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string oldUrl = HttpContext.Current.Request.RawUrl;
// 新聞頁面重寫規則:/News12.html → NewsDetails.aspx?NID=12
string pattern = @"^(.+)News(\d+).html(\?.*)*$";
string replace = "$1NewsDetails.aspx?NID=$2";
// 文化頁面重寫規則:/Culture12.html → CultureDetails.aspx?CID=12
string patternCul = @"^(.+)Culture(\d+).html(\?.*)*$";
string replaceCul = "$1CultureDetails.aspx?CID=$2";
if (Regex.IsMatch(oldUrl, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled))
{
string newUrl = Regex.Replace(oldUrl, pattern, replace, RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.Context.RewritePath(newUrl);
}
if (Regex.IsMatch(oldUrl, patternCul, RegexOptions.IgnoreCase | RegexOptions.Compiled))
{
string newUrl = Regex.Replace(oldUrl, patternCul, replaceCul, RegexOptions.Compiled | RegexOptions.IgnoreCase);
this.Context.RewritePath(newUrl);
}
}
Request.RawUrl)Regex.Replace 將其轉換為實際的 .aspx 頁面並帶入查詢參數Context.RewritePath 進行伺服器端重導向,瀏覽器網址列保持原樣此方法可同時實現多組重寫規則,只需依需求增減 pattern 與 replace 變數。重寫後將 GET 參數隱藏於友善網址中,不僅提升安全性,也讓使用者誤以為網站採用靜態頁面。只要伺服器支援,配合強大的正則表達式,幾乎能實現任意形式的 URL 重寫。