Richard Hart

Head of Something @ Somewhere
Kent, UK

My Music
My Photos

LinkedIn
Mastodon

Nginx proxy_pass a folder to WordPress

After a rash of security updates for WordPress, I finally buckled down to move our install of WordPress off to its own server. This would be easy if we were running the blog on it’s own domain, but it was actually living under /blog on our main domain for SEO reasons. Running nginx as a reverse proxy to WordPress on a different machine was not an easy task. A lot of guides did not seem to have the information I needed so here are the steps I took to get it working.

Add the proxy_pass definition to your nginx config:

location /blog/ {
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_set_header X-Forwarded-For $remote_addr;
  proxy_set_header X-Forwarded-Proto https;
  proxy_pass http://your-wordpress-ip-or-domain/;
}

Update your WordPress settings. This is the key to getting your site to work correctly. Leave the WordPress Address as where the site is hosted, but change the Site Address to be where URLs are to be written as linking to

Screenshot 2015-07-27 21.43.38

I also had to add a rewrite to my .htaccess file to remove trailing slashes:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteRule (.+)/$ http://www.yourdomain.com/blog/$1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>


Be warned that the permalinks section will suggest a .htaccess file which has /blog/ as the RewriteBase, but this just sends things into a redirect loop. Leave it as the standard root setting.

Make sure you also check that the canonical tags generated by your theme are correct. You want to be sure that any references on the WordPress Address URL canonicalise to Site Address URLs.