ASP.NET 301 Redirect In Master Pages

18. June 2009

Today I was asked if we could set up a 301 Redirect for all non “www” request. For example if someone requested http://robbihun.com/page/about-me.aspx it would automatically do a 301 (permanent) redirect to http://www.robbihun.com/page/about-me.aspx thus making all existing links (and SEO links) work without issue.

Basically all you have to do is check the requested url, check for the existance of the www. and if it is not present, set the HTTP Headers to do a 301 redirect to the same page to the www request.

 

I added the following to the master page – its not my favorite code ever, but it was quick to write and implement… and most importantly, works.

    protected void Page_Load(object sender, EventArgs e)
    {
        string requestPath = GetApplicationPath().ToLowerInvariant();
        string redirectPath = "~";

        if (!requestPath.Contains("www."))
        {
            if (requestPath.Contains("http://"))
            {
                redirectPath = reqPath.Substring(reqPath.IndexOf('/', 6));
                Response.Status = "301 Moved Permanently";
                Response.AddHeader("Location", "http://www.domain.com" + redirectPath);
            }
            else
            {
                redirectPath = requestPath.Substring(reqPath.IndexOf('/'));
                Response.Status = "301 Moved Permanently";
                Response.AddHeader("Location", "http://www.domain.com" + redirectPath);
            }
        }
    }
    public string GetApplicationPath()
    {
        string applicationPath = "";

        if (this.Page.Request.Url != null)
            applicationPath = this.Page.Request.Url.AbsoluteUri;
        return applicationPath;
    }

ASP.NET, General ,

Comments

Sai
Sai
1/19/2010 3:28:51 PM #
Thanks for this awesome tip. but i have question how can we use this code to redirect a domain name like for example i want to redirect www.mysiteltd.com to www.mysite.com.

how can i change your code to redirect the above situation.
Thanks appreciate it
Sai
1/20/2010 3:33:23 PM #
Sai,

If both of your domains are pointed to the same site you could use this technique to check for "mysiteltd" and redirect to "mysite".

If you have separate sites that the domains are pointed to there are other ways to do this - the easiest would be a basic html or javascript Meta-Refresh. Or if you are going to keep both domains and have control over your DNS you can set mysiteltd as a CNAME to mysite and configure your IIS Virtual Site headers to look for the second domain.

Add comment


(Will show your Gravatar icon)

Click to Refresh Captcha
biuquote
  • Comment
  • Preview
Loading