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:
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
.
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;
}
}
}
In each server block, replace example1.com
and example2.com
with the actual hostnames you want to forward requests for.
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
.
Save the configuration file and exit the editor.
Test the Nginx configuration to make sure there are no syntax errors:
nginx -t
nginx -s reload
Now, Nginx will forward requests to the appropriate backend server based on the hostname specified in the request.