Saturday, July 02, 2011

How to require SSL in IIS7 and Azure with Rewrite

imageThis is a tidy solution. Instead of requiring SSL (and giving 500s if they come over HTTP), use IIS URL Rewrite to check for HTTPS being off—and if so, redirect them (permanent 301) to the same path over SSL. The converse could also be done.

Good news is URL rewrite comes installed out of the box at Azure (looks like v1.2 and above).

Here's an example web.config showing the configuration to ensure that the secure directory requires SSL.

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="Enforce SSL" enabled="false" stopProcessing="true">
          <match url="/?(secure.*)" ignoreCase="true" />
          <conditions>
            <add input="{HTTPS}" pattern="off" />
          </conditions>
          <action type="Redirect" url="https://{SERVER_NAME}/{R:1}" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>