isHTTPS() recommended enhancement for load balancers

2 posts by 2 authors in: Forums > CMS Builder
Last Post: April 7, 2020   (RSS)

By tbcshifter - April 5, 2020

isHTTPS() doesn't work properly if your server is behind a load balancer. If the SSL cert is on the LB side, SERVER_PORT can be anything even if the original port was 443. This causes force_ssl to create an endless loop.

What I've done is add a line to check for headers which most load balancers populate. There may also be additional enhancements that could also be added here for different configurations, but this worked for me on Heroku and AWS.

function isHTTPS() {
  if (isset($_SERVER['HTTPS'])       && $_SERVER['HTTPS']       == 'on') { return true; }
  if (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443)  { return true; }
  if (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && @$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')  { return true; }
  if (isset($_SERVER['HTTP_X_FORWARDED_PORT']) && @$_SERVER['HTTP_X_FORWARDED_PORT'] == 443)  { return true; }
  return false;
}