nginx: redirect to a new domain except part of the URL pattern

Migrating to newer version of a web application from one domain to another has had it’s challenges. Since this web application has multiple projects, each project may be migrated one at a time. The goal is to redirect traffic to the new projects as they are migrated to the new domain. As part of that goal, the projects that have not been moved will remain accessible on the original web application server on the original domain. Simple enough with a redirect; however, the path has also changed. Adding it’s own set of challenges, that may be resolved.

The simplified version of the goal is this, redirect traffic similar to this example.

https://server1.olddomain.com/sites/Dept1 to
https://server2.newdomain.com/Dept1

Using nginx as the reverse proxy, this rule does the trick; however, only for this specific example.

server {
...
server_name server1.olddomain.com;
...
location /sites/Dept1 {
rewrite ^(.*) https://server2.newdomain.com/Dept1;
}

It fails, in an example like this.

https://server1.olddomain.com/sites/Dept1/subfolder/subfolder to
https://server2.newdomain.com/sites/Dept1/subfolder/subfolder

The resolution was not so obvious to me; however, with much trial and error the following rewrite rule seems to do the trick. The results are expected.

https://server1.olddomain.com/sites/Dept1/subfolder/subfolder to
https://server2.newdomain.com/Dept1/subfolder/subfolder

https://server1.olddomain.com/sites/Dept1 to
https://server2.newdomain.com/Dept1

<code>server {
...
server_name server1.olddomain.com;
...
location /sites/Dept1 {
rewrite ^/sites/(.*)$ https://server2.newdomain.com/$1 last;
}

Alternately, the following also works where https is replaced with $scheme.

rewrite ^/sites/(.*)$ $scheme://server2.newdomain.com/$1 last;

Source(s)
http://serverfault.com/questions/302509/how-to-quick-and-easy-remove-part-of-an-url-in-nginx-with-httprewritemodule