Redirect WWW To Non WWW Using Web.Config In IIS For ASP.NET Websites

Sameer Saini February 10, 2022
Redirect WWW To Non WWW Using Web.Config In IIS For ASP.NET Websites

When you first host your website, you will get a domain that is accessible via both WWW and non WWW versions of your domain.

For example, you bought a domain called example.com and you published a website on it.

You can browse this website using www.example.com or example.com and both of these URLs will lead you to the same destination. 

To the end-user, these both look the same and have no impact on how the website functions.

So why do we need a WWW to Non-WWW redirect?

Well, one reason could be just a personal preference. Some users or developers like to see their website in just one format, and that is a personal choice, there is no right or wrong in this.

I personally like to see my website without the www subdomain in front of the domain.

Another reason is for SEO.

SEO stands for Search Engine Optimization and is basically a technique in which bots from search engines like Google crawl your website for content.

That's how they are able to show the results when somebody searches for something relevant on Google.

When bots search your website, they will sometimes see the www domain and sometimes the non-www domain.

This ends up in a lot of extra crawled requests and pages and sometimes the correct page just gets lost.

SEO experts from Google also suggest that even though they treat both URLs as the same, you should have everything pointing to one URL, it doesn't matter which one.

You can choose for your website to go to WWW all the time or you can configure it to redirect to non-WWW. This will achieve consistency.

Now that we have understood why it's important to redirect WWW to non-WWW or the other way, let's see how we can do it.

Redirect WWW to NON-WWW in Web.Config

If you have hosted or published an ASP.NET website, and you want to redirect your www website calls to non-www calls, we will write a redirect rule in the Web.Config and that will handle our redirects when a call comes to the server.

If you don't see a Web.Config file, you can create one in your solution and the next time you deploy, your website will take the configuration from this web.config file. This is what an empty web.config looks like:

We add rules to the redirect inside the web.config like this


 Inside the rules element, we add our rule for redirecting www to non www like below:


Just change "yourwebsiteurl" to the domain url that you want to setup the redirection for.

Overall it looks like this: