Quick programming tip for servers behind load balancers

If you’re using PHP and wanting to check to make sure the incoming connections came over HTTPS, you are probably using the $_SERVER['HTTPS'] variable.

The problem is, if your servers are behind a load balancer which handles SSL encryption for you, this method of checking won’t work.  Fortunately, there are other headers added by the load balancer you can use to detect SSL.  They are the X-Forwarded-* headers.

For example:
$headers["X-Forwarded-For"] == 123.45.67.89 (because $_SERVER['REMOTE_ADDR'] is going to give you the load balancer’s IP address)
$headers["X-Forwarded-Port"] == 443
$headers["X-Forwarded-Proto"] == https

These headers should work with all loadbalancers, including Amazon’s ELB on EC2.