Vishwamohan

Welcome to Vishwa's blog - Technology, Spirituality and More...

Redirect non-www to www using rewrite

There are multiple scenario in which you would like to redirect your domain to always to a standard address possibly www.domain.com

 

If you’re using IIS 7 or higher, URL Rewrite is a valuable tool, well worth installing and using.

 

One common use of URL Rewrite is redirecting http://domain.com to http://www.domain.com .   Many people are doing this for search engine optimization (SEO) so that search engines only see the one site, rather than two sites.

 

Some people may have multiple blog hosted on the same account with different domain names. And you do not want the end-user landing to a wrong domain if he or she did not provide www along with domain name. So what is the solution.

 

One solution is open IIS Manager and double-click on the “URL Rewrite” icon and then add rules. Well, this may not be very user friendly.

 

The other solution is much simpler, just open the web.config file and then …In the <system.webServer> section, add the following:

 

If you like Wildcards

 
<rewrite>
   <rules>
     <rule name="Redirect domain.com to www" patternSyntax="Wildcard" stopProcessing="true">
       <match url="*" />
       <conditions>
         <add input="{HTTP_HOST}" pattern="domain.com" />
       </conditions>
       <action type="Redirect" url="http://www.domain.com/{R:0}" />
     </rule>
   </rules>
   </rewrite> 


If you like Regular Expressions

<rewrite>
    <rules>
      <rule name="Redirects to www.domain.com" patternSyntax="ECMAScript" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAny">
          <add input="{HTTP_HOST}" pattern="^domain.*(com|net)$" />
          <add input="{HTTP_HOST}" pattern="^(www.)?mydomain2.(com|net)$" />
          <add input="{HTTP_HOST}" pattern="^www.domain.net$" />
        </conditions>
        <action type="Redirect" url="http://www.domain.com/{R:0}" />
      </rules>
    </rules>
  </rewrite>
Loading