How to fix WordPress HTTPS issues when behind an Amazon Load Balancer?

I've had this issue before. When running WordPress (or other PHP scripts) behind Amazon's EC2 Load Balancer, the scripts do not realize they are being ran on the https:// protocol and results in issues such as endless redirect loops, and HTTPS warnings ("Some content on this page is being requested in a non-secure way...").

I found a solution here, but requires modifying WordPress core, which is no good for updatability: https://wordpress.org/support/topic/when-behind-amazon-web-services-elastic-load-balancer-causes-endless-redirect

Is there a way to fix this without modifying WordPress core? I am using Apache 2.2.


Solution 1:

Like the link, you gave suggested, for WordPress the issue lies in the is_ssl() function, which like most PHP software explicitly checks the $_SERVER['HTTPS'] and $_SERVER['SERVER_PORT'] to check if the current page is being accessed in the https:// context.

When your page is accessed over HTTPS, but the Amazon Load Balancer is performing SSL offloading and actually requesting your content on the non-SSL port 80, the webserver, PHP, or anything else for that matter, does not understand or see that it's being accessed over https://.

The fix for this is that Amazon's ELB sends the de-facto standard X-Forwarded-Proto HTTP header, which we can use to figure out which protocol the client is actually using on the other side of the Load Balancer.

With Apache 2.2, you could use something along the lines of:

<IfModule mod_setenvif.c>
  SetEnvIf X-Forwarded-Proto "^https$" HTTPS
</IfModule>

This simply reads the X-Forwarded-Proto header. If this value equals https then the HTTPS environment variable is set to 1. PHP will see this environment variable, and eventually, it will become $_SERVER['HTTPS'] that equals 1 -- just like it would be for a "real" native SSL request.

Solution 2:

Another option from the WordPress documentation is to add this to your wp-config.php:

if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
       $_SERVER['HTTPS']='on';

Solution 3:

In case anyone else was looking for the Nginx equivalent to this, here's what you need to do:

For rewrite setup you should add the following under the server block:

if ($http_x_forwarded_proto != 'https') {
    rewrite ^ https://$host$request_uri? permanent;
}

And for setting the HTTPS param you should add the following under the location ~ \.php$ block:

if ($http_x_forwarded_proto = 'https') {
    set $fe_https 'on';
}
fastcgi_param HTTPS $fe_https;

Remember to remove any other fastcgi_param HTTPS command if you have any (I had it in my fastcgi_params file).