Asp.net mvc 301 从 www.domain.com 重定向到 domain.com [英] Asp.net mvc 301 redirect from www.domain.com to domain.com
问题描述
我们在 domain.com 上有一个网站,也可以通过指向 domain.com 的 www.domain.com 的 CNAME 条目访问该网站.我们希望使用 301 重定向将 www.domain.com 的所有访问者重定向到 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.
在 IIS7 中安装 HTTP 重定向功能是最好的方法.
在我们的例子中,其他约束迫使我们在应用程序级别执行此操作.
In our case, other constraints force us to do this at application level.
这是我们在 global.asax 中用来执行重定向的代码:
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();
}
}
这篇关于Asp.net mvc 301 从 www.domain.com 重定向到 domain.com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!