Redirect non-www to www URLs using htaccess/web.config (Apache/IIS)

On an Apache server

Most users reading this article will likely be on an Apache server. Here are the steps you’ll need.
Use your host’s file manager or an FTP program to access your .htaccess file. Note that it has a dot preceding it.
If you don’t find, check to see if there’s a htaccess.txt file, which can be renamed to .htaccess if it came with your CMS (edit the file and check its contents to be sure). If there isn’t a htaccess.txt file either, simply create a new file called .htaccess.
Then simply insert either of the following lines and modify the code with your domain:
Redirect non-www to www
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]
If you had a “RewriteEngine On” in your htaccess file already, insert the above code just after the line reading: “RewriteEngine On”.
Afterward, check your site (including some internal pages) and try different www and non-www combinations of your domain to see if the redirect is working as expected.
On an IIS server
On a Windows (IIS) server, find your web.config file and make the following rule changes to your rules tag:
Redirect non-www to www

 <configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="Redirect to www" stopProcessing="true">
 <match url=".*" />
 <conditions>
 <add input="{HTTP_HOST}" pattern="^yourdomain.com$" />
 </conditions>
 <action type="Redirect" url="http://www.yourdomain.com/{R:0}"
 redirectType="Permanent" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer> 
 </configuration>
 
Redirect www to non-www

 <configuration>
 <system.webServer>
 <rewrite>
 <rules>
 <rule name="Redirect to non-www" stopProcessing="true">
 <match url=".*" >
 <conditions>
 <add input="{HTTP_HOST}" pattern="^yourdomain.com$" />
 </conditions>
 <action type="Redirect" url="http://yourdomain.com/{R:0}" redirectType="Permanent" />
 </rule>
 </rules>
 </rewrite>
 </system.webServer> 
 </configuration>
 
Afterward, check your site, including some internal pages, and try different www and non-www combinations of your domain to see if the redirect is working as expected.

Leave a Reply