The IIS rewrite module is a really powerful feature in IIS. It gives you power to set up rules to handle how requests for specific URLs are handled.

You can:

  • Perform redirects
  • Send custom responses
  • Stop HTTP requests based on the rules in the rewrite module.

Redirecting to HTTPS

There are multiple ways in IIS to redirect a URL to HTTPS. The HTTP Redirect feature is useful, but it only redirects to a specific URL. If you want to redirect to HTTPS and retain the full URL requested with page and querystring I prefer to use the URL Rewrite module.

Installing IIS URL Rewrite Feature

The URL Rewrite module works with IIS 7 and above, it’s currently on versioon 2.0.

You can install the URL Rewrite 2.0 module using:

Web Platform Installer

Web Platform Installer. Or directly from it’s page at http://www.iis.net/downloads/microsoft/url-rewrite

Chocolatey

https://chocolatey.org/packages/UrlRewrite This does require IIS (obviously I hope?)

choco install urlrewrite

Powershell

The following Powershell script does the following: .Creates an msi directory on the c: .Downloads the Web Platform Installer .Installs the Web Platform Installer .Calls the Web Platform Installer to install the URL Rewrite 2.0 feature

Create-Item c:/msi -Type Directory
Invoke-WebRequest 'http://download.microsoft.com/download/C/F/F/CFF3A0B8-99D4-41A2-AE1A-496C08BEB904/WebPlatformInstaller_amd64_en-US.msi' -OutFile c:/msi/WebPlatformInstaller_amd64_en-US.msi
Start-Process 'c:/msi/WebPlatformInstaller_amd64_en-US.msi' '/qn' -PassThru | Wait-Process
cd 'C:/Program Files/Microsoft/Web Platform Installer'; .\WebpiCmd.exe /Install /Products:'UrlRewrite2' /AcceptEULA /Log:c:/msi/WebpiCmd.log

Setting up the rule

If you load up IIS you will now see the URL Rewrite Module.

–Screen shot

Click into it and you are greeted with the following screen.

– screen shot

You can set up the rules in here, but I actually prefer directly in the web.config. I think it allows you to understand the rules better than the GUI shows.

So load up your web.config and add the following new section:

<rewrite>
    <rules>
        <rule name="Redirect to HTTPS" stopProcessing="true">
            <match url="(.*)"/>
            <conditions>
                <add input="{HTTPS}" pattern="^OFF$"/>
            </conditions>
            <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
        </rule>
    </rules>
</rewrite>

Now if you go back to the URL Rewrite module in IIS you will see how it’s set up the rules.

Summary

The URL Rewrite module is a powerful feature than gives you full control of what is going on.

Comments

About

Founded in 2009, Odity is a software consultancy based in the United Kingdom.

Social Links

Our Bunker

United Kingdom.