Today we are going to understand how can we fix a WordPress loading issue (CSS and JS loading issue) behind the Google Cloud Load Balancer or AWS Load Balancer.
Generally, When we host a WordPress site directly with Google Cloud Compute Engine VM instance or AWS EC2 instance. It's loading perfectly fine.
But once we added this WordPress server behind any Load Balancer either from GCP Load Balancer or AWS Load Balancer, you site will completely broken, means the CSS and JS of your site not loaded properly.
The reason for this is - When you put a load balancer in front of WordPress, you need to modify wp-config.php
to process the HTTP header HTTP_X_FORWARDED_PROTO
to detect the protocol that the user is using and not the protocol the load balancer is using to connect to your backend.
To fix this issue, we have to make following changes in the wp-config.php file and add the below code snippet on the top of wp-config.php file -
Google Cloud Platform Load Balancer:
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
{
$_SERVER['HTTPS']='on';
}
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'];
}
Amazon Web Services Load Balancer:
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: Through Apache Configuration
<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.
Same can be achieved through wp-config.php file
if (strpos($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') !== false)
$_SERVER['HTTPS']='on';