Search code examples
nginxsubdomainserver-name

How to configure a proxy with a subdomain servername


I have the following vhost configuration in nginx:

upstream mybackendsrv {
    server backend:5432;
}

server {
    listen 80;
    server_name sub.domain.org;

    location / {
        proxy_pass http://mybackendsrv;
    }
}

When I use a server_name like sub.domain.org, I get the default nginx fallback and my server is not matched.

When I use a server_name like customroute, I get the correct behaviour and my server is matched.

I googled this issue a bit and I believe that subdomain matching is supported in nginx so I'm not sure what's wrong. I checked the access.log and error.log and I get no relevant log.

Any idea how to diagnose this?

I should be able to display route matching logic in debug mode in nginx, but I'm not sure how to accomplish this.

Any help is appreciated.


Solution

  • After investigation, it seems the problem was unrelated to the fact that our URL was a subdomain.

    To debug the situation, a $host variable was introduced in the log_format directive in /etc/nginx/nginx.conf:

    log_format  main  '$remote_addr - $host - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    

    This $host variable allowed to understand that there was a problem with sub.domain.org: when we accessed sub.domain.org, the host was changed to the NGINX server's hostname, contrary to customroute which host was not changed.

    It appears sub.domain.org was not a simple DNS config but was an Apache proxy pass configuration. Apache was changing the host name when passing the request, causing NGINX to not match the rewritten host because it received in the request host it's own host instead of the target host.

    To correct this behavior, we had to add the following configuration in Apache: ProxyPreserveHost on.

    Once we restarted Apache, it the host was preserved and our server_name sub.domain.org was correctly matched in NGINX.