I'm Andrew Hoefling, and I work for FileOnQ as a Lead Software Engineer building mobile technologies for Government, Financial and First Responders using Xamarin. 

 

Web.Config Rewrite HTTP to HTTPS in ASP.NET


Many browsers are displaying security warnings to users when the websites don't serve traffic over HTTPS and it is becoming more and more important to serve traffic securely. When working in an IIS environment the user can still access your HTTP site and forcing them to access the site securely using HTTPS can be a challenge.

Prerequisites

Before getting started you need an ASP.NET Web Application running on IIS. If you like using the Cloud Providers such as Microsoft Azure this same technique will also work and will require less maintaince.

IIS Rewrite Module

The IIS Rewrite Module is critical for this to work without it, the rewrite rules will be ignored. If you are using a Web App in Microsoft Azure it is included by default.

Web.Config Rewrite

Add the following code inside the <system.webServer> node of the web.config XML

Force HTTP to HTTPS Rewrite Rule

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

Considerations

The IIS Rewrite rule to force all traffice to HTTPS is very powerful but sometimes you want most of your traffic re-written and not all of your traffic. When I deploy apps to an Azure Web App and use Let's Encrypt to generate my SSL Certificate I can't force all of my traffic to HTTPS. The Let's Encrypt Azure Web App extension requires an unsecure HTTP request to be made to a folder called .well-known. If my Azure Web App only serves HTTPS traffic Let's Encrypt will fail everytime you try to renew.

Rewrite Exceptions

Adding an exception to the rewrite is very easy, just add the following line to the conditions

<add input="{REQUEST_URI}" pattern=".well-known/" negate="true"/>

Here is the complete Rewrite Rule with the exception

<rewrite>
  <rules>
    <rule name="HTTP to HTTPS" stopProcessing="true"> 
     <match url="(.*)" /> 
     <conditions> 
       <add input="{HTTPS}" pattern="off" ignoreCase="true" />
       <add input="{REQUEST_URI}" pattern=".well-known/" negate="true"/>
     </conditions> 
     <action type="Redirect" url="https://{HTTP_HOST}/{R:1}" />
   </rule> 
  </rules>
</rewrite>

 

-Happy Coding


Share

Tags

.NETConfigurationIISWeb.ConfigSSLHTTPSRewrite