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:


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="^(.+)://" />
    <action type="Redirect" url="{C:2}://www.{C:1}/{R:0}" />

This will result in the following URLs:

  • 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