How to serve different content for domain.com and apis.domain.com from nginx

Vivek V Dwivedi asked:

On my nginx server (ubuntu 18.04), I want to host domain.com and apis.domain.com, where domain.com is one index.html file and apis.domain.com is a proxy to my node js api, which is running on port 3001.

I have 2 files in /etc/nginx/sites-available folder called domain.com and apis.domain.com and here are the contents from those files.

// domain.com
server {
        listen 80;
        listen [::]:80;

        root /var/www/domain.com/html/production;
        index index.html

        server_name domain.com www.domain.com;

        location / {
                try_files $uri $uri/ =404;
        }
}

// apis.domain.com
upstream domain_apis {
        server 127.0.0.1:3001;
        keepalive 64;
}

server {
    listen 80;
    server_name apis.domain.com;

 location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        proxy_pass http://domain_apis/;
        proxy_redirect off;
        proxy_read_timeout 240s;
    }
}

when I hit domain.com, things are working fine. But when I hit apis.domain.com, it serves the page from domain.com root folder. I have replaced reverse proxy with simple server with another subdomain, but it always serves the root domain.

Any ideas on how to debug this and how to check if requests are hitting the correct block?

My answer:


In your server block for apis.domain.com you have forgotten the listen directive:

     listen [::]:80;

Thus whenever you access nginx via IPv6 it would never reach that server block and would only reach the domain.com server block.

Because IPv6 is the default protocol and IPv4 is the legacy protocol and only used when IPv6 is unavailable, it will be used preferentially whenever possible. Thus you need to have nginx listen on both IPv4 and IPv6. (More info)


View the full question and any other answers on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.