301 global redirects from a domain to www.domain

Can I use the Global.asax initial request to redirect everything

from mydomain.domain to www.mydomain.domain?

If this is true, how can I do this?

+5
source share
2 answers
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();
  }
}
+4
source

A few minor changes in Jan's answer made me work for me:

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();
    }
}

The change was to use the BeginRequest event and set currentUrl to HttpContext.Current.Request.Url instead of HttpContext.Current.Request.Path. Cm.:

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

+9
source

All Articles