Nginx proxy_pass proxies to the same server

nginx

I have an Nginx testing environment set up where I have 2 server blocks. The first is using server_name .DomainA.; and the second is using server_name DomainB.com; Along with this, my client machine's hosts file has set www.DomainA.test to the server's IP and my server's hosts file sets DomainB.com to 127.0.0.1.

I am using:

curl www.DomainA.test/a_test

to hit my initial location:

location /a_test {
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_pass http://DomainB.com/b_test;
}

Now, for my DomainB.com server block, I have this location:

location /b_test {
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $remote_addr;
    return 200 "<html><head><title>Test :)</title></head><body>You are speaking to $host (B server)<br/>You have found $host:$server_port $request_uri</body></html>\n";
}

With this configuration, for the above curl, I get a 404. I discovered by accident that if I add a /b_test location for the .DomainA. server, the result from there will be returned, so it is obviously not looking to resolve DomainB.com. Adding an upstream for DomainB.com (pointing solely to 127.0.0.1) does not change the result.

Is this a quirk of Nginx, where it won't look to other server blocks when I proxy_pass to the same IP address? Or perhaps I've missed something in the documentation? Is this something that can/should be handled with rewrite or proxy_redirect? My goal is to just send a request to www.DomainA.test/a_test and have Nginx forward it behind the scenes to DomainB.com/b_test, with all this forwarding invisible to the client.

Best Answer

The trouble is that I am setting the Host to $host in location /a_test. It needs to be set to "DomainB.com" instead.