URL Rewrite (301 Redirect)

URL Rewrite 301 Server side permanent redirect

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


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.



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

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


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" + 
            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);

Use full Links

URL Rewrite
Google and SEO
Best practices when moving your site

Related Tags


32 Tutorials
27 Snippets
6 Products


Contact Us

Contact us

Stay Connected