zen of coding

Checking for SSL and then some…

A simple way to check and enforce SSL can be done by using the RequestHandler component.
Here’s an example:

private function checkHttps() {
  if(!$this->RequestHandler->isSSL()) {
    return $this->redirect('https://' . env('SERVER_NAME') . $this->here);

Simple enough, right?

Yet there is a little caveat, which causes a problem in a specific load balanced environment.
To give a little further insight into the whole situation, it is not uncommon nowadays to setup your SSL certs on the load balancer and have it handle the decryption, while passing “regular” HTTP requests down to the web servers.

So what happens in this case?
If we use the approach described above what would happen is that load balancer would handle the HTTPS request and pass a regular HTTP request to apache (or your web server).
At this point the application would say: “Wait this is not secure, redirect the URL to HTTPS… and so on to the point where we’d get stuck in the infinite loop of redirects).

How to fix?

private function checkHttps() {
  $lbEnv = env('HTTP_X_FORWARDED_PROTO');
  if (!is_null($lbEnv) && (env('HTTP_X_FORWARDED_PROTO') != 'https')) {
    return $this->redirect('https://' . env('SERVER_NAME') . $this->here);
  • Pingback: Tweets that mention Checking for SSL and then some… | nuts and bolts of cakephp -- Topsy.com()

  • I thought you’re supposed to handle SSL via the Security component, no?


  • teknoid

    For the second scenario it may not be possible to check with RequestHandler. On the other hand there is no need to load a component, for something so simple.

    It’s still just PHP after all.

  • Steven

    Why would you do this instead of an apache redirect?

  • teknoid


    You are more than welcome to share apache redirect solution for the given case, hopefully it’ll benefit anyone experiencing the same scenario.


  • I figured it out by tweaking in file /cake/config/paths.php by replacing below line:

    if (env(‘HTTPS’)) {
    $s =’s’;

    by this:

    $headers = apache_request_headers();
    $s =’s’;

    Now it is working perfectly in load-balancer also.

  • hugobq

    You really save my day.. I was stuck in the infinite loop of redirects!

  • Rgdg121

    thank you very much..

%d bloggers like this: