Thursday, October 10, 2013

Add Prefix www automatically in URL in ASP.Net

When opening a website from the browser, some people don't like to write the www prefix and open the website without it. Thus, to maintain the uniformity, ASP.Net provides a facility to add automatically, the www prefix in case it's not found.

You just need to add the following rewriter rule in your web.config file:

<rewrite>
  <rules>
    <rule name="Add WWW prefix" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^yourdomain\.com$" />
      </conditions>
      <action type="Redirect" url="http://www.yourdomain.com/{R:0}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

This will automatically add the www prefix in the URL if not found.

Same thing can also be done to remove the prefix www as given in the below code below:

<rewrite>
  <rules>
    <rule name="Remove WWW prefix" stopProcessing="true">
      <match url="(.*)" ignoreCase="true" />
      <conditions>
        <add input="{HTTP_HOST}" pattern="^www\.yourdomain\.com$" />
      </conditions>
      <action type="Redirect" url="http://yourdomain.com/{R:1}" redirectType="Permanent" />
    </rule>
  </rules>
</rewrite>

The above <rewrite> code is to be written within the <system.webServer> tag of web.config file.

You can now subscribe to this blog to get email notifications of the articles posted.

Thanks & Regards,
Munjal

No comments:

Post a Comment