Prepending www to 2nd level domain names

A fairly common request for URL Rewrite is to prepend a www to all 2nd level domains, regardless of the domain name. Consider the following domain names:

  • http://domain1.com
  • http://domain2.net
  • https://domain3.org

Following is an IIS URL Rewrite rule which will add the www to domain names without requiring you to create multiple rules. It will also maintain the http or https while doing so.

<rule name="Prepend www to 2nd level domain names" enabled="true" stopProcessing="true">
    <match url=".*" />
    <conditions trackAllCaptures="true">
        <add input="{HTTP_HOST}" pattern="^([^.]+\.[^.]+)$" />
        <add input="{CACHE_URL}" pattern="^(.+)://" />
    </conditions>
    <action type="Redirect" url="{C:2}://www.{C:1}/{R:0}" />
</rule>

This will result in the following URLs:

  • http://www.domain1.com
  • http://www.domain2.net
  • https://www.domain3.org
  • If you want to exclude a particular 2nd level domain name then simply add a negated third condition for the domain name which you want to exclude:

    <add input="{HTTP_HOST}" pattern="$domain4\.com^" negate="true" />

    No Comments