Computers & ProgrammingBasic NetworkingComputers & NetworkingWeb Development

How to Automatically Redirect From HTTP to HTTPS

The topic of automatically redirecting users that access your website from a 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, working around in IIS using error pages, and 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 easiest ways to accomplish this while providing the most flexibility. Here is some example code that can be used on ASP.NET websites 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 website that require HTTPS access.

VB.Net

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

Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))

C#

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 advantage of URL Rewriting. Of course, before you can allow SSL connections on your web server, you’ll need to configure the web server accordingly.

Leave a Comment

Your email address will not be published.

Scroll to Top