Wednesday, 21 April 2010

Redirect all visits to HTTPS

Today I implemented HTTPS for a site after it had already been running for some time over normal HTTP. I had to redirect all incoming traffic to its HTTPS equivalent, honouring the full path and parameters. For instance, an incoming visit to http://www.myshop.com/products.aspx?widget=1234 needed to seamlessly become https://www.myshop.com/products.apsx?widget=1234 .

I added this to the masterpage and all seems sweet:
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
       If Request.IsSecureConnection = False And _
            Not Request.Url.Host.Contains("localhost") Then
            Response.Redirect(Request.Url.AbsoluteUri.Replace("http://", "https://"))
        End If
End Sub

I also more recently had to do this in C# for a site using URL rewriting. This is how it looks:

Response.Redirect(Request.Url.Scheme.Replace("http", "https") + "://" + Request.Url.Authority + Request.RawUrl);

No comments:

Post a Comment

Comments are moderated, so you'll have to wait a little bit before they appear!