在ASP.NET虚拟主机上实现URL重写(UrlRewrite)

搜索引擎喜欢.html或者.htm的页面,不喜欢.aspx?id=123&p=345 所以从用户友好和SEO来说都有必要URL重写。

在自己主机上实现可以采用如下方法:

 但是在虚拟主机上没有权限去修改iis,也没有权限去安装iis rewrite之类的iis插件。只能修改下global.asax.cs的BeginRequest函数了:

protected void Application_BeginRequest(object sender, EventArgs e)
{
            
string oldUrl = HttpContext.Current.Request.RawUrl;

            
///输入地址/webform1/123.html
            
///重写后地址/webform1.aspx?id=123

            string pattern = @"^(.+)webform1/(\d+)\.html(\?.*)*$";
            
string replace = "$1webform1.aspx?id=$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);
            }

}
这样当你输入地址/WebForm1/123.html会被重定向到:/WebForm1.aspx?id=123。点击这儿下载示例代码和工程。
原文地址:https://www.cnblogs.com/Mainz/p/UrlRewrite_HostServer_AspNet.html