0

On my Nginx server (Ubuntu 18.04), I want to host example.com and apis.example.com, where example.com is one index.html file and apis.example.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 example.com and apis.example.com and here are the contents from those files.

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

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

        server_name example.com www.example.com;

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

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

server {
    listen 80;
    server_name apis.example.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 example.com, things are working fine. But when I hit apis.example.com, it serves the page from example.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?

Christopher H
  • 338
  • 2
  • 16

1 Answers1

2

In your server block for apis.example.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 example.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)

Michael Hampton
  • 237,123
  • 42
  • 477
  • 940