Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bzamecnik/f5b6e8bf57c808edd244cd6e743c4a3c to your computer and use it in GitHub Desktop.
Save bzamecnik/f5b6e8bf57c808edd244cd6e743c4a3c to your computer and use it in GitHub Desktop.
Nginx proxy for Wordpress.com on custom domain with subpath.

Let's say we can a blog hosted as Wordpress.com but visible on our custom domain in subpath due to SEO. WordPress.com supports changing domain/subdomain but not path.

We could either make our own installation, change hosting provier or make nginx proxy with URL rewrites.

This tutorial is inpsired by http://marsbard.github.io/2016-07-30-replace-urls-behind-nginx-reverse-proxy/.

Nginx needs the ngx_http_sub_module. You can check with: nginx -V.

nginx.conf - put into the server section and restart:

# nginx rule to make a wordpress.com site visible at subpath of our domain.
# Wordpress.com allows setting domain/subdomain, but not custom path.
# We have to proxy requests and rewrite base URLs rendered by WP to our site.
# Original base URL: https://example.wordpress.com/
# User facing base URL: https://example.com/blog/
# For administration better use the original domain.

# path on our site (visible to users)
location /blog/ {
  # request get proxied to this site (hosted by wordpress.com)
  proxy_pass https://example.wordpress.com/;
  proxy_set_header X-Forwarded-Host $host;
  proxy_set_header X-Forwarded-Proto $scheme;
  # disable compression to make substitution work
  proxy_set_header Accept-Encoding "";

  # substitute URL rendered by wordpress.com to our location
  # http://marsbard.github.io/2016-07-30-replace-urls-behind-nginx-reverse-proxy/
  # plain URL:
  sub_filter 'https://example.wordpress.com' '$scheme://$host/blog';
  # escaped in JS:
  sub_filter 'https:\/\/example.wordpress.com' '$scheme:\/\/$host\/blog';
  # redirect in JS in URL parameters:
  sub_filter 'redirect_to=https%3A%2F%2Fexample.wordpress.com%2F' 'redirect_to=$scheme%3A%2F%2F$host%2Fblog%2F';
  # replace many times
  sub_filter_once off;
  # keep the last modified header
  sub_filter_last_modified on;
}

Various places where base URL appears in plain or escaped forms:

https://example.wordpress.com
https:\/\/example.wordpress.com
https:\/\/example.wordpress.com\/wp-login.php?redirect_to=https%3A%2F%2Fexample.wordpress.com%2F
@nicolasfguillaume
Copy link

Thank you so much!! The only solution that worked for me, after hours of search

@iman4000
Copy link

my resources not loaded but wordpress is good in subdirectory.
any idea about why resources not loaded corectly?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment