15

I am trying to implement URL redirect for the website rather than doing it page by page. I want to do it in the global.asax file. Below is the code i have defined.

I want to have http://website.net as my main url & want to have a permanent URL redirect if someone types in http://www.website.net.

Unfortunately it is not working for the live website. Can anyone point out the problem in the code. The code doesn't generate any error.

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup

    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
    {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
    }

}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Learning
  • 19,469
  • 39
  • 180
  • 373

5 Answers5

17

Main problem: Your're doing the above stuff in Application_Start - which is only executed once. You should hook up with each request. Try this:

void Application_BeginRequest(object sender, EventArgs e) 
{
    // Code that runs on every request

    if (HttpContext.Current.Request.Url.ToString().ToLower().Contains("http://website.net"))
    {
        HttpContext.Current.Response.Status = "301 Moved Permanently";
        HttpContext.Current.Response.AddHeader("Location", Request.Url.ToString().ToLower().Replace("http://website.net", "http://www.website.net"));
    }

}

An even better approach would be to use URL rewriting, which can be configured from within Web.Config:

Microsoft rewriting module - Force www on url Or remove www from url

Community
  • 1
  • 1
MartinHN
  • 19,542
  • 19
  • 89
  • 131
  • Oops My mistake. Should have noticed... I am planning to implement url routing rather than rewriting and i had issue with rewriting due to the structure and no. of query-string in certain pages. Appreciate your reply. Thanks – Learning May 20 '12 at 12:44
  • It is better to use StartsWith instead of Conatins like this : if (HttpContext.Current.Request.Url.ToString().ToLower().StartsWith("http://website.net")) – keivan kashani Feb 05 '19 at 06:07
  • @keivankashani No it's not better. Some urls start with http or https and your method does not work in this cases. – Farzin Kanzi Oct 06 '19 at 11:33
13

If using IIS 7 or higher, the simplest solution is to use the httpRedirect element in your web.config.

<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
     <add wildcard="/MyOldAspFile.aspx" destination="/MyNewFile.aspx" />
     <add wildcard="/MyOldHtmlFile.html" destination="/MyNewFile.aspx" />
</httpRedirect>

This method is very powerful, for example if you have changed the domain but the pages are the same, you have just to add:

<system.webServer> 
    <httpRedirect enabled="true" childOnly="true" destination="http://www.mynewdomain.com/" /> 
</system.webServer>

I wrote a small article here: ASP.NET 301 permanent redirects: the best solution

Igor
  • 383
  • 3
  • 11
9

Version 4 of .NET actually has an improved function for single page implementation - the redirectpermanent.

Response.RedirectPermanent(NEW_URL);

JNF
  • 3,696
  • 3
  • 31
  • 64
5

Building on previous correct and helpful answers, here are a couple specific examples. Assuming you want to delete the old page (as I did), there are a couple of options.

OPTION 1: Modify the Global.asax

 void Application_BeginRequest(object sender, EventArgs e)
    {
        // Add permanent redirection for retired pages
        if (Request.Url.LocalPath.ToLower().StartsWith("/[OLD PAGE NAME]"))
        {
            Response.RedirectPermanent("/[NEW PAGE NAME]", false);
        }
    }

OPTION 2: Modify the web.config

<system.webServer>
    <httpRedirect enabled="true" httpResponseStatus="Permanent">
        <add wildcard="/[OLD PAGE NAME]" destination="/[NEW PAGE NAME]" />
    </httpRedirect>
</system.webServer>    
wloescher
  • 4,503
  • 2
  • 25
  • 27
3

if you didn't know what is application domain name ,use something like this

protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).Contains("localhost"))return;
        var leftPartOfUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority).ToLower();
        if (leftPartOfUrl.StartsWith("http") && leftPartOfUrl.Split('.').Length == 1)
        {
            var fullUrl = HttpContext.Current.Request.Url.ToString();
            HttpContext.Current.Response.Status = "301 Moved Permanently";
            HttpContext.Current.Response.StatusCode = 301;
            HttpContext.Current.Response.AddHeader("Location", fullUrl.Insert(fullUrl.IndexOf("://", StringComparison.Ordinal) + 3, "www."));
            HttpContext.Current.Response.End();
        }
    }