How to use nginx to proxy a subdirectory to a subdomain

It’s common to host a wordpress blog on a subdomain like https://blog.example.com on separate servers from the main site for various reasons.

For SEO purpose(Google thinks subdomain is a separate site), you may want to use https://example.com/blog for your blog but keeping the blog installation on original server. It’s simply to do this using a proxy server.

For example:

www.example.com/example.com is on server A.
blog.example.com is on server B.
We have a proxy server C.

Now, we need setup the proxy for main domain www.example.com on server C.

The nginx site conf will look like this:

# proxy subdirectory to subdomain
location /blog/ {
    proxy_pass https://blog.example.com;
    proxy_set_header Host blog.example.com;
    # strip /blog/ from the path
    rewrite /blog/(.*) /$1 break;
}

# proxy everything else to main domain server
location / {
    # pass everything to example.com server
    proxy_pass http://server_A_IP;
    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 http;

}

Test conf and restart nginx

nginx -t && systemctl restart nginx

Next, change main domain A record to the proxy server. Once DNS is propagated, you will need to install the SSL for main domain so that you can use https://example.com/blog to go to your blog.

certbot --nginx -d example.com

The only problem is that the links are still using the subdomain address blog.example.com. You can simple add following two lines in wp-config.php file to replace all subdomain links to the proxy address “example.com/blog”

define('WP_HOME', 'https://example.com/blog');
define('WP-SITEURL', 'https://example.com/blog');

Now, when you go to https://example.com/blog, you will see what you have on https://blog.example.com
All the blog posts/pages will also be translated to the proxy address like it’s hosting on the same server as the main domain.