web.config Redirect non-www to www

That often looked for website redirect from the non-www version of the website URL, address, to the www version.

In this case the redirect is for a Windows hosted website, using the web.config file to set the redirect rules.

I wish to avoid adding the redirect within the website coding. By taking advantage of the redirect rules within the web.config file. This will make them readily available and can be edited without recompiling the website code.

Access your website either using FTP or the editor/manager within the housing website control panel.

The file to be edited is located at the root of the website. This may be a directory down. Check if you have a directory such as public_html.

It’s easier to edit the content of the web.config file of is laid out correctly and colour coded. An HTML editor will make your life easier when editing.

Shown below is the code to add the redirect of the non-www address to www to be added to the web.config asp.net website configuration file:

<rewrite>    
    <rules> 
        <rule name="Canonical" stopProcessing="true"> <match url=".*" /> 
            <conditions> 
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" /> 
            </conditions> 
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" /> 
        </rule> 
</rewrite>

The above is to be added within the section <system.webserver>

As as a bonus below is the HTTPS version too!

<rewrite>    
    <rules> 
        <rule name="Redirect to HTTPS" stopProcessing="true"> 
            <match url="(.*)" /> 
            <conditions> 
                <add input="{HTTPS}" pattern="^OFF$" /> 
            </conditions> 
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" /> 
        </rule> 
    </rules> 
</rewrite>

Putting this all together gives:

<rewrite>    
    <rules> 
        <rule name="Canonical" stopProcessing="true"> <match url=".*" /> 
            <conditions> 
                <add input="{HTTP_HOST}" negate="true" pattern="^www\.([.a-zA-Z0-9]+)$" /> 
            </conditions> 
            <action type="Redirect" url="http://www.{HTTP_HOST}/{R:0}" redirectType="Permanent" /> 
        </rule> 
        <rule name="Redirect to HTTPS" stopProcessing="true"> 
            <match url="(.*)" /> 
            <conditions> 
                <add input="{HTTPS}" pattern="^OFF$" /> 
            </conditions> 
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="SeeOther" /> 
        </rule> 
    </rules> 
</rewrite>    

Technically it’s a 301 or 302 redirect. Looking at the code above it can be seen that I’ve used the redirectType parameter value of permanent showing the redirect to be of type 301. web.config rewrite rules to permanently redirect non-www to www.