Home > database >  nginx reverse-proxy for all subdomains except alredy defined
nginx reverse-proxy for all subdomains except alredy defined

Time:10-29

I have a rather simple question, i have an enviroment, where i have often changing subdomains, but some are also presistent, now i want to forward api.example.com to 1.2.3.4:8080 and all other incoming requests to 2.3.4.5:9090. My setup till now is that i forward all requests from the api subdomain points to 1.2.3.4:8080:

server {
        listen 80;
        listen [::]:80;
        server_name api.example.com;

        access_log /var/log/nginx/reverse-access.log;
        error_log /var/log/nginx/reverse-error.log;

        location / {
                    proxy_pass http://1.2.3.4:8080;
  }
}

Now i need a way to point all other subdomains to 2.3.4.5:9090.

CodePudding user response:

All you need is to dynamically resolve your subdomains. the following config will take care of your situation.

server {
        listen 80;
        listen [::]:80;
        server_name ~^(?<subdomain>. )\.example\.com;

        access_log /var/log/nginx/reverse-access.log;
        error_log /var/log/nginx/reverse-error.log;

        location / {
                    if ($subdomain = "api") {
                           proxy_pass http://1.2.3.4:8080;
                    }

                    proxy_pass http://2.3.4.5:9090;
        }
}

CodePudding user response:

Use default_server in listen. See docs.

server {
    listen 80;
    listen [::]:80;
    server_name api.example.com;

    location / {
        proxy_pass http://1.2.3.4:8080;
    }
}

server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;

    location / {
        proxy_pass http://2.3.4.5:9090;
    }
}
  • Related