1
votes

I am using the IIS URL Rewrite module on a Windows 2012 server. I only want to add a canonical www rule if a subdomain is missing (or an exact match on 'example.com').

The problem is the ready-made Canonical rewrite rule IIS creates rewrites all traffic (*) for all subdomains to www.

 <rule name="CanonicalHostNameRule1">
 <match url="(.*)" />
   <conditions>
      <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
   </conditions>
   <action type="Redirect" url="http://www.example.com/{R:1}" />
 </rule>

The problem is that I have multiple subdomains / applications under one site (and therefore one web.config).

I want

example.com

to go to

www.example.com

but to leave these and any other subdomain alone:

secure.example.com

profile.example.com

Do I need a more specific match regex or pattern?

More specifically, the secure subdomain uses https and a better encryption certificate.

2

2 Answers

2
votes

You're looking for everything that is not www.example.com. And that includes all other sub-domains.

Let's have a look at your condition:

 <add input="{HTTP_HOST}" pattern="^www\.example\.com$" negate="true" />
  • If www.example.com comes in --> match = true --> negate --> false --> nothing is changed (as you want)

  • If example.com comes in --> match = false --> negate --> true --> URL gets redirected (as you want)

  • If foo.example.com comes in --> match = false --> negate --> true --> URL get redirected (as you don't want)

To fix this, try this configuration:

<rule name="Redirect to www" stopProcessing="true">
    <match url="(.*)" />
    <conditions trackAllCaptures="true">
       <add input="{CACHE_URL}" pattern="^(.+)://" />
       <add input="{HTTP_HOST}" pattern="^example\.com$" />
    </conditions>
    <action type="Redirect" url="{C:1}://www.example.com/{R:1}" />
</rule>

The C:1 part is for the protocol (http and https).

Found here.

0
votes

This regex is better:

^(w{3}\.)?\w+\.com/

This regex will give you the option to get url with and without the www. and the / at the end, but still wont math a subdomain.