How to redirect Urls without www to with www – Permanent (301) Redirection in ASP.net

First, why should we redirect Urls without “www” to with “www” or vice versa?

Answer – If you site cares for search engine ranking then this is a must. Famous search engines like Google or Bing prefer that you have ONLY one domain associated with your website. In search engine world, “www.mydomain.com” and mydomain.com are considered two different domains. If you don’t redirect calls for mydomain.com to “www.mydomain.com”  Or vice-a-versa, crawler will treat these two as two different yet totally duplicate sites. Hence, your search engine ranking will have a negative impact.

Other than this important reason, you also might want to stick to one of these Urls to maintain your Social Media Like Counters e.g. Facebook will also consider two of these as two different sites.

This post is not about understanding the benefits of permanent redirection to one preferred domain url. For more information you can read this article by google.

Now lets get to fixing this issue in Asp.net. URL rewrite can be done in IIS or by using <rewrite> rule in Asp.net web.config file.

url_rewrite
Adding above code to web.config will permanent redirect (status code 301) all requests for mydomain.com to “www.mydomain.com” .

1) Inbound Rule – “.*” regex will match all request coming to web server for mydomain.com.

2) Condition – Regex pattern “^mydomain.com$” will match domain name without “www” prefix.

3) Action – Re-write action replaces the current query string with a substitution string. In other words, pattern specified in condition input will be replaced with url specified in action tag and we will force this as Permanent redirection Type (it goes with status 301).

If you are not familiar with Regex expressions, read this tutorial by Microsoft to know more.

To further better understand <rewrite> module and various attributes in-depth, I suggest reading this excellent article from Microsoft.

I hope this helps you reach the solution you were looking for.

 

Happy Coding!

Savita