URL Rewrite (301 Redirect)

URL Rewrite 301 Server side permanent redirect

Added by Nasir Mahmood updated on Monday, November 25, 2013

Problem:

Previously I was working on Search Engine Optimization for my site, I was shocked to know that mydomain.com and www.mydomain is not same. Search engines treat both domains as separate.

According to Google

"Once you've set your preferred domain, you may want to use a 301 redirect to redirect traffic from your non-preferred domain, so that other search engines and visitors know which version you prefer."

So our problem is to solve server side redirect (301 redirect) in ASP.Net.

Setup:

Web.Config:

We can achieve our task by adding following code in our web.config file.


<system.webServer>
    <rewrite>
        <rules>
            <rule name="Redirect to www" stopProcessing="true">
                <match url=".*" />
                <conditions>
                    <add input="{HTTP_HOST}" pattern="^mydomain.com$" />
                </conditions>
                <action type="Redirect" url="http://www.mydomain.com/{R:0}" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Programmatically:

We can also achieve our task programmatically by adding following code in our Global.asax file

void Application_BeginRequest(object sender, EventArgs e)
{    
    if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith("http://mydomain"))
    {
        string newurl = "";
        if (HttpContext.Current.Items["UrlRewritingNet.UrlRewriter.VirtualUrl"] != null)
        {
            newurl = "http://www.mydomain.com" + 
                     HttpContext.Current.Items["UrlRewritingNet.UrlRewriter.VirtualUrl"].ToString();
        }
        else
        {
            newurl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower()
                    .Replace("http://mydomain", "http://www.mydomain");
        }
        Response.Status = "301 Moved Permanently";
        Response.StatusCode = 301;
        Response.StatusDescription = "Moved Permanently";
        Response.AddHeader("Location", newurl);
        Response.End();
    }    
}

Use full Links

URL Rewrite
Google and SEO
Best practices when moving your site

Related Tags

About

29 Tutorials
25 Snippets
6 Products

More

Contact Us

Contact us

Stay Connected