Use WordPress on HTTPS site with load balancer

WordPress by default uses a pretty simple test to check if your site is running on https or http.

Published:

In wp-includes/load.php we find the following method:

function is_ssl() { if (isset($_SERVER['HTTPS'])) { if ('on' == strtolower( $_SERVER['HTTPS'])) { return true; } if ('1' == $_SERVER['HTTPS']) { return true; } } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) { return true; } return false; }

In short, if either server variable HTTPS is "on" or "1" or if server variable SERVER_PORT is "443", assume the site is running on https.

In a load balanced environment, this check might return false, even if the site is running on https.

Use phpinfo() to find what server variable is set instead. In my case, the server set server variable HTTP_X_PROTO to "https". You might find X_FORWARDED_PROTO or other variants.

To get WordPress to understand that it is running on https, I added the following code to wp-config.php:

if ($_SERVER['HTTP_X_PROTO'] == 'https') { $_SERVER['HTTPS'] = 'on'; }

I use rules in .htaccess to forward anyone accessing the http address to https. I'm effectively blocking access to my http adress.

Therefore I can even skip the check of server variables altogether and simply write this in wp-config.php:

$_SERVER['HTTPS'] = 'on';

Categories: PHP WordPress

Comments