How to reverse proxy to different places depending on subdomain in Nginx?

Solution 1:

Unless I completely misread your question: You simply set up server blocks for each sub-domain and the define the correct reverse proxy for the root of that subdomain i.e. something along the lines of:

 server {
        server_name subdomain1.example.com;
        location / {
            proxy_pass       http://hostname1:port1;
        }
 }
 server {
        server_name subdomain2.example.com;
        location / {
            proxy_pass       http://hostname2:port2;
        }
 }

Solution 2:

Pretty much the same way.

location /foo {
    rewrite ^/foo(.+)$ /$1 break;
    proxy_pass http://foo;
}

location /bar {
    rewrite ^/bar(.+)$ /$1 break;
    proxy_pass http://bar;
}