The typical way of reverse-proxying different subdomains to different places with Nginx is to install a unique server for each subdomain, like this:
server {
server_name subdomain1.example.com;
location / {
proxy_pass http://hostname1:port1;
}
}
server {
server_name subdomain2.example.com;
location / {
proxy_pass http://hostname2:port2;
}
}
Is it possible to achieve the same result within one single server block (e.g. server_name .example.com, without any specified subdomain), by specifying different locations within that server block?
If you specify different locations then it won't be the same result as you have the same
location /
in twoserver
blocks.Yes, it is possible.
First, set up a
map
to map domains intoproxy_pass
destinations:When nginx receives a request, it goes to
proxy_pass
directive. Then it resolves$dest
using themap
, 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.