Nginx – Nginx Reverse Proxy with Different Subdomains Configuration Issue

nginxPROXY

I have a setup involving the following domains:

  • site.com
  • abc.site.com
  • xyz.site.com

And the following two servers:

  • 12.34.56.78
  • 98.76.54.32

Basically, I am trying to shape my traffic as followed: CloudFlare -> 98.76.54.32 -> 12.34.56.78. So, the 98 IP acts as a reverse proxy, and the 12 IP acts as the destination/main server.

On CloudFlare I have all of these domains pointed to the reverse proxy server. The reverse proxy is running this configuration file, reverse-prox.conf:

server {
    listen 80;
    server_tokens off;

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

Now, on the main server, 12.34.56.78, I have the following configuration files:

abc.site.com

server {
    listen 80;
    listen [::]:80;

    root /var/www/abc;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name abc.site.com;

    location / {
        try_files $uri;
    }
}

xyz.site.com

server {
    listen 80;
    listen [::]:80;

    root /var/www/xyz;

    index index.php index.html index.htm index.nginx-debian.html;

    server_name xyz.site.com;

    location / {
        try_files $uri;
    }
}

I shortened the configuration files for convenience, but that's the gist of it.

It works near-flawlessly, but there is a problem. abc.site.com works correctly, but xyz.site.com shows the /abc/ folder instead of the /xyz/ folder. Not sure why this happens. There is no default configuration in either of the Nginx configurations (on both servers).

So, how do I fix this? Why does abc.site.com work correctly, but xyz.site.com display the same thing as abc.site.com (instead of its respective /xyz/ contents).

Best Answer

Why does abc.site.com work correctly, but xyz.site.com display the same thing as abc.site.com (instead of its respective /xyz/ contents).

Use proxy_set_header to pass Host request header from 98.76.54.32 to 12.34.56.78. By default, nginx doesn't proxy this Host header.

nginx sets Host request header to $proxy_host variable, which is the hostname/IP address and port set on your proxy_pass directive.

For example, on 98.76.54.32:

server {
    listen 80;
    server_tokens off;

    location / {
        proxy_set_header Host $host;
        proxy_pass http://12.34.56.78;
    }
}