Home Web.Config Rewrite HTTP to HTTPS in ASP.NET
Post
Cancel

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

1
2
3
4
5
6
7
8
9
10
11
<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

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

Here is the complete Rewrite Rule with the exception

1
2
3
4
5
6
7
8
9
10
11
12
<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

This post is licensed under CC BY 4.0 by the author.