Redirecting HTTP to HTTPS (SSL) on IIS, But Not on IIS Express

My rant in the previous post is that all sites should be on SSL. When you use SSL, it uses the secure HyperText Transfer Protocol (HTTPS). Web addresses that use SSL all start with https://. However, you don't really want to make your user type that in. If a user types www.example.com into the browser url line, the browser automatically sticks http:// onto the front. That http:// uses unencrypted HTTP, and automatically goes to port 80 by default.

But I want my site to be on 443 and use https. So when someone types www.example.com, I want the server to redirect to https://www.example.com. The trick is to install IIS rewrite on the server, then put the following into the web.config file:

                <rule name="HTTP to HTTPS redirect" stopprocessing="true">
                    <match url="(.*)">
                            <add ignorecase="true" input="{HTTP_HOST}"
                                negate="true" pattern="^localhost*">
                                <add ignorecase="true" input="{HTTPS}" pattern="off">
                        <action redirecttype="Found" type="Redirect"
        <modules runallmanagedmodulesforallrequests="true">

I've seen this basic XML in multiple places on the web, so don't know who the original author is to attribute it to. But I want to talk about my addition it.

The problem with the rewrite rules is  when you are testing. Your IIS Express test server isn't going to have the certificate to handle SSL traffic. So you want to turn off the rewrite rule when you are testing. The line that does that is:

<add ignorecase="true" input="{HTTP_HOST}" negate="true" pattern="^localhost*">

What that says is to ignore the rule as long as the web server name is localhost.

No comments :

Post a Comment