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);
  }
}

Related Posts

%d bloggers like this: