Nginx – Using a server_name variable in an nginx proxy_pass config

nginx

I have two back-ends with different data that I want to test my UI code against, so I'm trying to configure Nginx to allow me to switch between them based on URL.

So for example, the local URL https://ui.local.otherserver:80 would try my local files then proxy anything else to https://otherserver:80.

I'm trying to avoid having two server blocks as the config below is simplified and duplication is a pain.

The behaviour I'm seeing is that one of the back-ends works fine, and the other one gives me a 502 (Bad Gateway) error, but if I hard-code either server's name in the proxy_pass line it works as expected, i.e. successfully proxies to that specific server.

Any ideas what I'm doing wrong?

ssl             on;
ssl_certificate      /usr/local/etc/nginx/conf.d/cert.ui.crt;
ssl_certificate_key  /usr/local/etc/nginx/conf.d/cert.ui.key;

server {
    listen          443;
    listen          80;
    server_name     ~^ui\.local\.(?<backend>.+)$;
    expires         -1;
    access_log      /var/log/nginx/ui.access.log;
    error_log       /var/log/nginx/ui.error.log;

    root /Users/richard/Projects/ui/trunk/;

    location ~ ^(.*)$ {
        try_files $1 @platform;
    }
    location @platform {
        proxy_pass https://$backend:$port;
    }
}

Best Answer

502 is a Bad Gateway error, which means that nginx was unable to communicate with the backend. There should be a more detailed message in the nginx error log explaining what the communication error was. Have a look in /var/log/nginx/error.log (or similar) to find the actual cause.