Redirect WWW to Non-WWW using the Web.config

By now, most people know that websites’ SEO is dinged by Google when there is both a www and non-www url with the same content on both. Google (and Bing) treat them as two separate sites and they fight for pagerank as everyone else blows your two competing sites out of the water. I’ve had redirects set up on my WordPress blog for the past 4 years, which is pretty easy to do, but I recently moved my blog over to Ghost blogging engine and since it’s currently at version 0.5, it didn’t have this 301 redirect functionality built in, so I needed to roll my own. Since I was moving to Azure Websites, I needed to add a redirect to get this fixed in the web.config, so I thought I’d share it with you! 

Redirecting to non-www using the Web.config

You can always use IIS to explicity set up a redirect, but I find that these types of configurations are best done in the Web.config, since they are (1) more portable, (2) have the ability to be stored in source control, and (3) can be included in Web.config transformations if you want to get all fancy!

Here’s what you need to add to your Web.config:

<rewrite>
    <rules>
        <rule name="Redirect to non-www" stopProcessing="true">
            <match url="(.*)" negate="false"></match>
            <action type="Redirect" url="http://domain.com/{R:1}"></action>
            <conditions>
                <add input="{HTTP_HOST}" pattern="^domain\.com$" negate="true"></add>
            </conditions>
        </rule>
    </rules>
</rewrite>

 

Note: You’ll need to make sure that for redirecting a site like www.example.com to example.com, you’ll need to make sure that you’ve configured both of those domains to point to your website. If you never set up the www. site to point to your host, IIS and your Web.config will never be hit to do a redirection.

 

 

Collect Lost SEO

And that’s it! These redirects have huge effects on what I call “accidental” SEO. All over the internet you’ll find people in the habit of hand-linking to websites, and we’ve got a bad habit of just assuming www and non-www links are inter-changeable, when they’re not. Setting up these redirects will ensure you get credit for all (or many, many more) of the links to your site that are out there on the web.

Ryan Hayes

Ryan is a Microsoft MVP award winner with over eight years of software experience, working with big-name clients such as Discovery Channel, AOL, Toyota, and the National Academy of Sciences. Ryan has helped teams deliver award-winning applications that drive business processes, site traffic, and profit, putting his experience and creativity to work to build amazing solutions for the enterprise web, desktop and mobile platforms.