WordPress & Load balancing on Google Cloud Balancing

Viewed 936

I am setting up a WordPress site as a Google VM instance. I am using a load balancer & setting up the front end to manage the SSL (https) boundary & certificate. I set 'A' records to point to the load balancer using (non-ephemeral) URL (xxx.xxx.xxx.xxx) & I specified the appropriate google name servers. My WordPress site is a VM instance in an instance group. It should be communicating via HTTP since the HTTPS terminated at the load balancer. (thus effectively Google internal traffic on HTTP)

What should WordPress values be for WP_HOME & WP_SITEURL bearing in mind that they are behind the load balancer and behind the HTTPS/SSL boundary?

1 Answers

In most cases, you do not need to change WP_HOME & WP_SITEURL after a correct WordPress setup. Specify them as normal https://www.example.com. Change to your real website URL.

When WordPress is running behind a load balancer, your wp-config.php needs to be modified to process the HTTP header HTTP_X_FORWARDED_FORWARDED_PROTO to detect that the client connected to the load balancer with HTTPS. Place the following lines near the bottom of wp-config.php:

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

Next, if you are logging client access, you need to log the correct client IP address. The load balancer will add its IP address as the client making your logs report the load balancer IP address instead of the client's IP address.

Place the following lines after the previous lines (actually does not matter):

if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && !empty($_SERVER['HTTP_X_FORWARDED_FOR']) )
{
        $ips = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

        $_SERVER['REMOTE_ADDR'] = trim($ips[0]);
}
elseif ( isset($_SERVER['HTTP_X_REAL_IP']) && !empty($_SERVER['HTTP_X_REAL_IP']) )
{
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_X_REAL_IP'];
} elseif ( isset($_SERVER['HTTP_CLIENT_IP']) && !empty($_SERVER['HTTP_CLIENT_IP']) )
{
        $_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CLIENT_IP'];
}

Important Note:

You mentioned "Instance Group". For a Managed Instance Group (MIG) any changes that you make to a live running VM will be lost if the instance is recreated. This includes all changes to WordPress itself. You must either use an unmanaged instance group or recreate the image used for a managed instance group. There are exceptions such as using a shared independent MySQL server and storing all configuration files on Cloud Storage or NFS.

Related