37

I'm trying to write a URL rewrite rule to force a HTTPS connection. This should always happen except when a request is using localhost (e.g. http://localhost/mysite).

The rule is configured as following:

 <rule name="Redirect to https" enabled="true" stopProcessing="true">
      <match url="(.*)" negate="false" />
      <conditions trackAllCaptures="false">
           <add input="{HTTPS}" pattern="^OFF$" />
           <add input="{URL}" pattern="localhost" negate="true" />
      </conditions>
      <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
 </rule>

I also tried to use ^localhost and ^localhost/(.*) as a pattern for the URL condition with no help. Does anyone have an idea why this does not work and what a solution for this problem should be?

Justin Iurman
  • 18,954
  • 3
  • 35
  • 54
One of many
  • 547
  • 1
  • 4
  • 8

2 Answers2

53

Your code should look like this instead

<rule name="Redirect to https" enabled="true" stopProcessing="true">
   <match url="(.*)" />
   <conditions logicalGrouping="MatchAll" trackAllCaptures="false">
      <add input="{HTTPS}" pattern="off" />
      <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
   </conditions>
   <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
</rule>
Justin Iurman
  • 18,954
  • 3
  • 35
  • 54
0

Combined URL Rewrite based answers from How to redirect HTTP to HTTPS in MVC application (IIS7.5) and above and added "127.0.0.1" too.

I also see {REQUEST_URI} being used instead of {R:1} and pattern="^OFF$" instead of pattern="off".

At pattern added the ignoreCase="true" too, though it might be the default (same goes for enabled="true" for the rule, handy to have there if you want to turn some rule off when debugging some rule chain)

However, wondering based on https://serverfault.com/questions/224039/iis-url-rewrite-http-to-https-with-port/418530#418530 if one needs to use SERVER_NAME instead of HTTP_HOST in the pattern if non-default ports are used and specify the port in the Redirect url too

  <system.webServer>

  <!-- … -->

    <rewrite>
        <rules>

            <rule name="HTTP to HTTPS redirect (excluding localhost)" enabled="true" stopProcessing="true">
                <match url="(.*)" />
                <conditions>
                    <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    <add input="{HTTP_HOST}" pattern="localhost" negate="true" />
                    <add input="{HTTP_HOST}" pattern="127.0.0.1" negate="true" />
                </conditions>
                <action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" />
            </rule>

        </rules>
    </rewrite>

  <!-- … -->

</system.webServer>
George Birbilis
  • 2,782
  • 2
  • 33
  • 35