Detecting and Redirecting Http to Https

There was a recent thread on the mach-ii mailing list where a user wanted to detect whether a request was being made via http or https.

This is quite a common step developers take when working on a site with secure (SSL) and non-secure areas. As the list is mach-ii there are a couple of obvious framework specific options to take, those being Filters and Plugins. Although Peter Farrel does have an sslPlugin available, I liked the approach put forward by Matt Osbun:

1
2
3
<cfif Compare(cgi.SERVER_PORT,443)>
  <cflocation url="https://#cgi.server_name##cgi.path_info#?#cgi.query_string#" addtoken="false"/>
</cfif>

Now I know a lot of people don’t like using CGI scoped variables, even the more common ones, so I thought I’d try it out with getPageContext().

1
2
3
4
5
6
<!--- set up the getRequest method for easy access --->
<cfset oRequest = getPageContext().getRequest() />

<cfif compare(oRequest.getServerPort(), 443)>
  <cflocation url="https://#oRequest.getServerName()##oRequest.getRequestURI()#?#oRequest.getQueryString()#" addtoken="false" />
</cfif>

As you can see it’s a little bit longer, but I believe is a safer option than relying on CGI variables.

A slight modification (using getRequest()) is testing the isSecure() which ”Returns true if this protocol is secure”:

1
2
3
4
5
6
<!--- set up the getRequest method for easy access --->
<cfset oRequest = getPageContext().getRequest() />

<cfif NOT oRequest.isSecure()>
  <cflocation url="https://#oRequest.getServerName()##oRequest.getRequestURI()#?#oRequest.getQueryString()#" addtoken="false" />
</cfif>

I’m still (slowly) making my way through getPageContext(), it can provide an absolute wealth of knowledge for the ColdFusion programmer. You can view the 1.4 pagecontext docs here and the servletrequest docs here.

Comments