web.config redirect non-www to www

iis, url-rewriting, web-config

Solution

For a safer rule that works for both `Match Any` and `Match All` situations, you can use the Rewrite Map solution. It’s a perfectly good solution with the only drawback being the ever so slight extra effort to set it up since you need to create a rewrite map before you create the rule. In other words, if you choose to use this as your sole method of handling the protocol, you’ll be safe.

You can create a Rewrite Map called MapProtocol, you can use `{MapProtocol:{HTTPS}}` for the protocol within any rule action.

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

Reference

Problem

I need to redirect non-www URLs to www URL for both HTTP and HTTPS URLs. I tried following rules in `web.config`. ``` <rule name="Redirect to WWW" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTP_HOST}" pattern="^example.com$" /> </conditions> <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" /> </rule> <rule name="Redirect to WWW https" stopProcessing="true"> <match url=".*" /> <conditions> <add input="{HTTPS}" pattern="^example.com$" /> </conditions> <action type="Redirect" url="https://www.example.com/{R:0}" redirectType="Permanent" /> </rule> ``` It works perfectly for non-ssl URL but in case of SSL it redirect from `https://example.com` to `http://www.example.com`.

Original source