How to Automatically Redirect From HTTP to HTTPS

Friday, October 28, 2011

The topic of automatically redirecting users that access your web site from an non-secure connection (HTTP) to a secure connection (HTTPS) has been around for quite some time. If you search the web, you'll find various ways of doing this such as by using vbscript code in the html page, a work around in IIS using error pages, and by creating multiple websites using different ports and redirecting users between sites.

I have tried all of these methods and have found that managing this in code is one of the easier ways to accomplish this while providing the most flexibility. Here is some example code that can be used on ASP.NET web sites that use either VB.NET or C# in the code-behind pages.

You would place the code in the Sub Page_Load Procedure. If you are using a Master Page, you can place this code in the Master Page.vb file (code-behind). Otherwise, you can add it only to the pages in your web site that require HTTPS access.

If Not Request.IsSecureConnection Then
Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))

if (!Request.IsSecureConnection)
Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"));

Additionally, if you are running IIS 7.0 or greater, I would recommend that you take advatage of URL Rewriting. Of course, before you can allow SSL connections on your webserver, you'll need to configure the webserver accordingly.

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources