How to configure multiple servers for reverse proxy in Nginx
To configure Nginx with multiple server reverse proxy, you need to edit the nginx.conf configuration file. The specific steps are as follows:
- Open the nginx.conf file, usually located in the /etc/nginx/ directory.
- Add a server block within the http block to represent each target server for the reverse proxy.
- http {
server {
listen 80;
server_name example1.com;location / {
forward requests to http://backend1;
}
}server {
listen 80;
server_name example2.com;location / {
forward requests to http://backend2;
}
}# Add more server blocks…
} - In the above example, two reverse proxies have been set up to route to target servers example1.com and example2.com, respectively leading to backend1 and backend2.
- Below the http block, add an upstream block to define the target server for reverse proxy.
- http {
upstream backend1 {
server backend1.example.com;
}upstream backend2 {
server backend2.example.com;
}# Add more upstream blocks…
} - In the above example, backend1 and backend2 point to the actual target server addresses.
- Save the configuration file and restart the Nginx server.
- Restart the nginx service using the systemctl command.
This completes the Nginx multi-server reverse proxy configuration. When accessing example1.com, Nginx will forward the request to the backend1 server; and when accessing example2.com, Nginx will forward the request to the backend2 server.