Asp.net MVC 301 www.domain.com重定向到domain.com
我们必须在domain.com一个网站,这也是通过一个CNAME条目www.domain.com指向回domain.com访问。我们希望所有访问者www.domain.com重定向使用301重定向到domain.com的。是什么在asp.net mvc的实现这一目标的最佳方式是什么?在Global.asax中?
We have a website at domain.com, which is also accessible via a CNAME entry for www.domain.com that points back to domain.com. We'd like all visitors to www.domain.com to be redirected to domain.com using a 301 redirect. What's the best way to implement this in asp.net mvc? In global.asax?
我承认在应用层面做的,这是不期望按照该意见的问题。
I accept that doing this at application level is non-desirable as per the comments to the question.
安装在HTTP重定向IIS7的特点是做到这一点的最好办法。
在我们的例子中,其他方面的限制迫使我们在应用层面做到这一点。
In our case, other constraints force us to do this at application level.
下面是我们在Global.asax的用于执行重定向的code:
Here is the code that we use in global.asax to perform the redirect:
private static readonly Regex wwwRegex =
new Regex(@"www\.(?<mainDomain>.*)",
RegexOptions.Compiled
| RegexOptions.IgnoreCase
| RegexOptions.Singleline);
protected void Application_BeginRequest(Object sender, EventArgs e)
{
string hostName = Request.Headers["x-forwarded-host"];
hostName = string.IsNullOrEmpty(hostName) ? Request.Url.Host : hostName;
Match match = wwwRegex.Match(hostName);
if (match.Success)
{
string mainDomain = match.Groups["mainDomain"].Value;
var builder=new UriBuilder(Request.Url)
{
Host = mainDomain
};
string redirectUrl = builder.Uri.ToString();
Response.Clear();
Response.StatusCode = 301;
Response.StatusDescription = "Moved Permanently";
Response.AddHeader("Location", redirectUrl);
Response.End();
}
}