I have multiple subdomains, all pointing to one machine, and one IP address. On this machine, I want to have nginx acting as a reverse proxy, and depending on which subdomain was used to access the machine, I want it to reverse proxy to a different server. All the examples I've seen of using nginx as a reverse proxy use location, but as I understand that only works for the path, not for different subdomains. How can I achieve what I want?

  • 2
    This might be a bit too broad. Can you post more about what you've tried already?
    – Will
    Commented Feb 1, 2016 at 5:47

2 Answers 2


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;
  • Sorry for late response, but I got it working! Commented Feb 4, 2016 at 1:00
  • This is magic, and you're a wizard!
    – Birb
    Commented Sep 24, 2020 at 22:13
  • Is it possible to access those addresses over https? I have an A-RECORD for subdomain.example.com. Do I need some more configuration to enable ssl access?
    – elano7
    Commented Oct 23, 2022 at 14:31
  • Now if I hit the IP address for example.com, the requests are sent to the first server. How can prevent that? Commented Feb 28 at 7:39
  • 1
    @Xapadoan Technically when no domain or subdomain matches the default server is used. The default server is the first one listed in the nginx.conf file, unless you include the default_server parameter to the listen directive to explicitly designate a server as the default. - nginx.org/en/docs/http/ngx_http_core_module.html#listen
    – HBruijn
    Commented May 2 at 15:31

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;
  • How does this work for subdomains though? The location and regex seem to be specifically for a path.
    – DBrown
    Commented Mar 2, 2022 at 14:58
  • 1
    To be honest, seems like I've clearly misread the question. :)
    – drookie
    Commented Mar 4, 2022 at 14:10
  • Hehe. We've all been there. 😉
    – DBrown
    Commented Mar 9, 2022 at 12:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .