When setting up a website, even if it’s just a generic blog like this one, it’s good to encrypt traffic to and from it using SSL.

Obtaining certificates

If you’re hosting a site on it’s own custom domain name rather than using a free hosting provider then you’ll likely need to get your own domain specific certificates rather than using the encryption of the hosting site. This site is hosted in Azure but with a custom domain so I need a certificate in order to use SSL on it. Happily certificates can be obtained for free from providers such as Let’s Encrypt. The only problem with getting a certificate for a site which you don’t directly host yourself is that in order to be issued with a certificate you need to prove you own the domain and without control of the underlying machine that’s pretty hard to do. Luckily there’s a good description of how to get certificates issued to sites hosted in Azure here, which although slightly convoluted, does work (and is free).

Enabling automatic HTTPS redirection the old way

In older ASP.NET web projects prior to ASP.NET Core it’s possible to force HTTPS usage by adding the following code to the system.webServer section of the web.config file of the site.

		<rule name="HTTP to HTTPS redirect" stopProcessing="true">
			<match url="(.*)"/>
				<add input="{HTTPS}" pattern="off" ignoreCase="true"/>
			<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent"/>
		<rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
			<match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*"/>
				<add input="{HTTPS}" pattern="on" ignoreCase="true"/>
			<action type="Rewrite" value="max-age=31536000"/>

Enabling automatic HTTPS redirection the ASP.NET Core way

In an ASP.NET Core project it’s slightly more complicated and there’s various ways of achieving the desired redirection but happily since the 1.1.0 release of ASP.NET Core there’s an offical Microsoft package for URL rewrites that can be used for this task. To begin with, install the NuGet package Microsoft.AspNetCore.Rewrite. Once this has installed it’s as simple as updating the Configure method in Startup.cs with the following code to ensure HTTPS is used.

// Redirect all HTTP requests to HTTPS
RewriteOptions options = new RewriteOptions();


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *