How to proxy a server based on domain name of request using nginx?

There is a situation where firstly all current requests should work as they currently working for certain domain name. For example www.hello.com

A dynamic dns is going to point to the same static ip of www.hello.com server (somedomain.dnsdynamic.com ---> XXX.XXX.XXX.XXX)

All requests, both GET, POST, etc. to be proxied to another server with hostname finalserver.example.com. (note that this server does not have a static ip, so the hostname must be used)

Proxy should only work when the www.hello.com server gets a request with server name somedomain.dnsdynamic.com

Already tried keeping in mind this answer but failed, either getting 502 bad gateway or 404 page not found


Solution 1:

If i understand you correctly, you could try defining two Virtual Hosts :

  • one for www.hello.com that serves the local web server content

  • another for somedomain.dnsdynamic.com that proxies to finalserver.example.com

Something like this :

    server {
      listen       80;
      server_name  www.hello.com;
      root /var/www;
      index   index.html;
    }

    server {
      listen       80;
      server_name  somedomain.dnsdynamic.com;

      location / {
        proxy_pass  http://finalserver.example.com;
      }
    }