Nginx: rewrite sub-folder to root and keep old WordPress links valid

Labsy asked:

I am struggling with NginX rewrites and redirects, but with only half success. Would appreciate some help.


Customer has 4 domains, which they want to point to all to same WordPress installation. Ok, I found nice WP Plugin (Multiple Domain) to accomplish that.

Previous WP install was inside /wp/ folder, which I had to move to root to be able for Multiple Domains plugin to work.

So I had to add NginX options to deal with previous /wp/ sub-folder for two reasons:

  • SEO and Google indexes all still point to /wp/ URLs, which would be dead without below rewrite
  • Web site designer hard-coded some links to images and some other things with /wp/ included in URL, so the below rewrite deals with this problem, too

Now ALL belwo works, and the best part is, that URL keeps the domain as it was entered (does not redirect to main domain): –> –>

location ^~ /wp/(.+) {
rewrite ^/wp/(.+)$ $1 last;

YES, all is working fine, EXCEPT when /wp/ is called without parameters: –> 404 –> 404

I also tried (.*), but did not help.

As it is configured now, all 4 domains work OK and fine with /wp/ in the middle of URL string, like this: –> (this is great!)

The only problem persists, when /wp is at the end: –> (does NOT rewrite/redirect, which is NOT ok)

My answer:

Your regex mandates the trailing slash after /wp to be present to match, but you say that you don’t want that.

location ^~ /wp/(.+) {
     rewrite ^/wp/(.+)$ $1 last;

So just make the trailing slash optional. For that matter you don’t really need the location; you can just place the rewrite directly in the appropriate server block.

rewrite ^/wp(/.+) $1 last;

View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.