Redirecting HTTP to HTTPS with the IIS URL Rewrite Module

I should use TLS

Hi folks. I've been working on my HTTP web server the past couple of weeks. It's pretty good so far. It uses the managed thread pool, does asynchronous request handling, tokenization (like %CURRENTDATE%, etc.) server-side includes, SSL/TLS support, can run multiple websites simultaneously, etc. It seems really fast, but I haven't put it through any serious load tests yet.  My original goal was to use it to completely replace this blog and content management system (IIS and BlogEngine.NET,) but now I'm starting to think that won't happen. Mainly because I would need to convert years worth of content to a new format, and I would want to preserve the URLs so that if anyone on the internet had ever linked to any of my blog posts, they wouldn't all turn to 404s when I made the switch. That's actually more daunting to me than writing a server and a CMS.



So I'm taking a break from that and instead improving what I've already got here. One thing I've always wanted to do but never got around to was redirecting HTTP to HTTPS. We should be using SSL/TLS to encrypt our web traffic whenever possible. Especially when it's this simple:

First, open IIS Manager, and use Web Platform Installer to install the URL Rewrite 2.0 module:

Install URL Rewrite


Now at the server level, open URL Rewrite and add a new blank rule:

Add Blank Rule


Next you want to match (.*) regex pattern:

Edit the rule


And finally add the following condition:


Condition


And that's all there is to it!  This is of course assuming that you've got an SSL certificate bound to the website already, and that you're listening on both ports 80 and 443.

Note that you can also do this exact same thing by editing your web.config file by hand:


    
<system.WebServer>
   ...
   <rewrite>
      <globalrules>
        <rule name="Redirect to HTTPS" stopprocessing="true" enabled="true">
          <match url="(.*)"></match>
          <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"></action>
          <conditions>
            <add pattern="^OFF$" input="{HTTPS}"></add>
          </conditions>
        </rule>
      </globalrules>
    </rewrite>
</system.WebServer>

And finally, a tip: Don't put resources such as images in your website that are sourced from HTTP, regardless if they're from your own server or someone else's. Use relative paths (or at least the https prefix) instead. Web browsers typically complain or even refuse to load "insecure" content on a secure page.

Comments are closed