我们在domain.com上有一个网站,也可以通过指向domain.com的CNAME条目的www.domain.com访问。我们希望将所有访问www.domain.com的访问者重定向到使用301重定向的domain.com。在asp.net mvc中,最好的实现方式是什么?在global.asax中吗?
我接受在应用程序层面这样做是不理想的,正如问题评论中所述。
安装IIS7中的HTTP重定向功能是最好的方法来完成此操作。
在我们的情况下,其他限制迫使我们在应用程序层面上执行此操作。
以下是我们在global.asax中使用的代码来执行重定向:
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();
}
}