全局301从域重定向到www.domain

时间:2010-01-21 18:51:20

标签: asp.net vb.net http-status-code-301 global-asax

我可以使用Global.asax的begin请求来重定向所有内容,

mydomain.domain www.mydomain.domain

如果这个是真的,我该怎么做?

2 个答案:

答案 0 :(得分:11)

对Jan的回答进行了一些细微的修改,这对我有用:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    string currentUrl = HttpContext.Current.Request.Url.ToString().ToLower(); 
    if (currentUrl.StartsWith("http://mydomain"))
    {
        Response.Status = "301 Moved Permanently";
        Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain"));
        Response.End();
    }
}

更改是使用BeginRequest事件并将currentUrl设置为HttpContext.Current.Request.Url而不是HttpContext.Current.Request.Path。见:

http://www.mycsharpcorner.com/Post.aspx?postID=40

答案 1 :(得分:5)

protected void Application_PreRequestHandlerExecute(Object sender, EventArgs e)
{
  string currentUrl = HttpContext.Current.Request.Path.ToLower();
  if(currentUrl.StartsWith("http://mydomain"))
  {
    Response.Status = "301 Moved Permanently";
    Response.AddHeader("Location", currentUrl.Replace("http://mydomain", "http://www.mydomain"));
    Response.End();
  }
}