0

I have an MVC4 application running on HTTP and HTTPS. Bsaically I want to ensure that all non-www requests direct to the www. version regardless of what protocol they are using. I am struggling to define this in URL Rewrite as my web.config rules is failing to load the site when adding the below code to the <server.webserver> node

<rewrite>
  <rules>
    <rule name="Redirect to www" stopProcessing="true">
      <match url="(.*)" />
      <conditions trackAllCaptures="false">
        <add input="{HTTP_HOST}" pattern="^domain.com$" />
      </conditions>
      <action type="Redirect" 
        url="{MapProtocol:{HTTPS}}://www.domain.com/{R:1}" />
    </rule>
  </rules>
  <rewriteMaps>
    <rewriteMap name="MapProtocol">
      <add key="on" value="https" />
      <add key="off" value="http" />
    </rewriteMap>
  </rewriteMaps>
</rewrite>

Any advice on how to create the redirect in IIS would be great

Liam
  • 27,717
  • 28
  • 128
  • 190
CR41G14
  • 5,464
  • 5
  • 43
  • 64
  • 2
    Normally this is done using DNS, just create a `CNAME` pointing from www to your domain. – Rosdi Kasim May 21 '15 at 13:17
  • 1
    @RosdiKasim: That depends on the required behaviour: if you want the address to be rewritten in the user's browser, you're not going to get that from a `CNAME`. – Dan Puzey May 21 '15 at 13:19

1 Answers1

2

When I add such a rule using IIS, this gets added to the Web.config:

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

In the pattern-part of the condition you have ^domain.com$ whereas I have ^www\.domain\.com$

Kristof Claes
  • 10,797
  • 3
  • 30
  • 42