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.

Situation:

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):

domainA.com

domainB.com/?cat=7 –> domainB.com/news

domainC.com/wp/something –> domainC.com/something

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

Problem?
YES, all is working fine, EXCEPT when /wp/ is called without parameters:

domainA.com/wp –> 404

domainB.com/wp –> 404

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

EDIT
As it is configured now, all 4 domains work OK and fine with /wp/ in the middle of URL string, like this:

domain.com/wp/news –> domain.com/news (this is great!)

The only problem persists, when /wp is at the end:

domain.com/wp –> domain.com/wp (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.