Daniel's Blog

Making WordPress on a Google VM work

The setup

The sales and marketing team is responsible for the marketing website that is at our root domain: amigocloud.com

A developer helped them setup a virtual machine and install WordPress on it. After configuring the domain, it turned into an infinite redirect error. Requests would come in to https://amigocloud.com, and it would error out in the browser as each one would return a 301 redirect.

I was asked to take a look.

The traffic flow goes as such:

  1. Request is received by a Google External Load Balancer
  2. If it is HTTP, a 301 redirect to HTTPS is returned, if it is HTTPS , then the network endpoint performs the SSL Termination as it has a Google Managed Certificate and then sends the HTTP data to the virtual machine.
  3. The Apache web server on the virtual machine receives the HTTP data and sends it to the WordPress PHP application, which then generates the page and sends it back.

The problem

The WordPress application needs to be configured to return links with HTTPS. Also, it needs to know not to send a 301 redirect when it receives HTTP traffic as that will always happen. The infinite redirect is caused by WordPress receiving the HTTP and sending back an HTTPS redirect even though the request was HTTP to begin with

The fix

First, I checked the Apache web server. I found that requests indeed had the X-Forwared-For-Proto and X-Forwareded-For set. So, I did a quick check for these in the wp-config.php to ensure that $_SERVER['HTTPS']='on' is set if the request was forwarded with an HTTPS protocol.

Then I set the WP_HOME and WP_SITEURL to the HTTPS URL to ensure that links will have HTTPS in them.

The full text I added was here:

/*
 * Daniel Caldwell
 *
 * I added this as the Google External HTTPS load balancer is
 * handling the SSL termination. So any requests to the instance
 * group servers will be receiving HTTP traffic on port 80.
 *
 * I used the Apache forensics log to verify that the X-Forwared-For-Proto
 * header is sent (along with X-Forwareded-For). So we can tell the
 * WordPress server that the protocol was originally HTTPS. This will
 * prevent the infinite redirect that occurs when you define the WP_SITEURL
 * and WP_HOME as HTTPS, but the WordPress server receives HTTP and sends
 * a redirect to HTTPS.
 */

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


/*
 * Daniel Caldwell
 *
 * Used these to fix home and site URL issues when the admin console setting
 * needed to be reverted because of the infinite redirect issue.
 *
 *
define('WP_HOME', 'https://amigocloud.com');
define('WP_SITEURL', 'https://amigocloud.com');
**/

The end

In conclusion, the site can now receive HTTP , but return HTTPS links and won't perform a HTTPS redirect.