nginx proxy_pass of different subdomains to different locations within one server block

Yes, it is possible.

First, set up a map to map domains into proxy_pass destinations:

map $host $dest {
    www1.example.com 192.168.10.10:8001;
    www2.example.com 192.168.10.11:8002;
    default 192.168.10.12;
}

server {
    server_name *.example.com;

    proxy_pass http://$dest;
}

When nginx receives a request, it goes to proxy_pass directive. Then it resolves $dest using the map, which maps different virtual host names to destinations. Then nginx proxies the request using the resolved destination.

Remember to set up the default destination properly. Every public web server receives requests for all kinds of domain names. Typically you want to return 404 on unknown virtual hosts.


If you specify different locations then it won't be the same result as you have the same location / in two server blocks.