How to configure Nginx to forward requests to a different server based on hostname?

To configure Nginx to forward requests to a different server based on the hostname, you can use the server blocks feature. Here's a step-by-step guide:

  1. Open the Nginx configuration file. The location of the file varies depending on your operating system. For example, on Ubuntu, it is typically located at /etc/nginx/nginx.conf or /etc/nginx/sites-available/default.

  2. Inside the http block, define multiple server blocks for each hostname you want to forward requests to a different server. Here's an example:

http { server { listen 80; server_name example1.com; location / { proxy_pass http://server1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } server { listen 80; server_name example2.com; location / { proxy_pass http://server2; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } } }
  1. In each server block, replace example1.com and example2.com with the actual hostnames you want to forward requests for.

  2. In the proxy_pass directive, specify the URL or IP address of the backend server you want to forward requests to. For example, http://server1 or http://192.168.1.100:8080.

  3. Save the configuration file and exit the editor.

  4. Test the Nginx configuration to make sure there are no syntax errors:

nginx -t
  1. If the configuration test is successful, reload Nginx to apply the changes:
nginx -s reload

Now, Nginx will forward requests to the appropriate backend server based on the hostname specified in the request.