Monday 26 February 2018

Running a non-https Wordpress site behind nginx that performs TLS termination

I was in the situation the other day where I had a fresh installation of a wordpress site which was sitting behind a reverse proxy (nginx in this case) which was terminating the SSL / TLS.

Now my initial thought was that this should work: users connect over HTTPS to the nginx, nginx proxies the request over HTTP to the wordpress server (httpd.) However after setting up the site I noticed that the formatting of the site was out and on close inspection noticed that my browser was blocking style sheets because they were being referenced as http://..... rather than https://.... We can verify this from within the Network Tab in the chrome developers tools (F12.)

So instead we need to instruct wordpress to use https when it's serving clients from nginx. However be aware that we will need to instruct nginx to send the 'X-Forwarded-Proto' HTTP header to httpd - although not all load balancers support this.

The 'X-Forwarded-Proto' header allows downstream servers (httpd) in this case to be aware of what protocol the client connecting to the upstream server (nginx) is using (https in this case.)

We should firstly add the following stanzas just below:

if ($_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')
 $_SERVER['HTTPS']='on';

if (isset($_SERVER["HTTP_X_FORWARDED_FOR"])) {
 $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_X_FORWARDED_FOR"];
}

The second stanza ensures the clients IP is recorded accurately in the logs (opposed to the upstream load balancers.)

We need to add the following headers in our nginx vhost config:

location / {
  proxy_pass ...........
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header X-Forwarded-Proto $scheme;
}

Restart nginx and httpd and we should now have a fully working wordpress site!

0 comments:

Post a Comment