65.9K
CodeProject is changing. Read more.
Home

Simple HTTPS Switching

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.42/5 (8 votes)

Aug 11, 2006

CPOL

2 min read

viewsIcon

36551

A simple way to switch from HTTP to HTTPS without re-writing links.

Introduction

So you have a site all put together, and many users and other sites link to your site. But then, you start having content that justifies SSL. Perhaps, the whole site does not need SSL, but only a directory or a single page here and there. The problem is that this is going to break all kinds of links, either from external users, or from pages in your own website. This can mean a lot of rework to prevent untold number of users getting 403.4 errors from IIS.

The Problem

When you are sitting on a page which does not require SSL, the browser assumes that the page your are going to will also not require SSL if it does not know any better. You can tell it the page does require SSL, but you have to fully qualify the URL in order to do so. Virtual and Root paths are not going to cut it here.

The Plan

IIS has a tab on its properties that will catch client-driven errors such as a 403.4 error. The 403.4 means that https:// is required, and is thrown when a user goes to a page with just http://. You can change what IIS does so that if it throws this error, it will return a message, send a file, or (as in our case) go to a URL.

Sample image

I created a page called /errors/ssl.aspx in my site. Here is the code...

Partial Class Errors_SSL _
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, _
              ByVal e As System.EventArgs) Handles Me.Load
        Dim lsURL As String = Request.Url.Query

        lsURL = lsURL.Substring(lsURL.IndexOf("://" & Request.Url.Host))
        lsURL = lsURL.Replace(":80", "")
        lsURL = "HTTPS" + lsURL
        lsURL = Server.UrlDecode(lsURL)
        Response.Redirect(lsURL)
    End Sub
End Class

This works because when the error is thrown, IIS returns the error code followed by the offending request as such...

http://localhost/errors/ssl.aspx?403
http://localhost/SomeSSLPage.aspx?id=52

We can parse this and redirect the user to the correct link. I noticed every now and then that IIS will throw the port into your request, so in my case, I always just took it out. I also don't show any HTML on this page, so the worst that happens is the user gets a quick white flash that looks like a post back. You could expand on this idea and handle 404s and the like as well.