To install and configure Nginx as a reverse proxy and load balancer on CentOS or Red Hat, you can follow these steps:
- Install the EPEL repository if it is not already installed on your system. EPEL provides additional packages that are not available in the official CentOS or Red Hat repositories. You can install it by running the following command:
sudo yum install epel-release
- Install Nginx by running the following command:
sudo yum install nginx
- Start and enable the Nginx service by running the following commands:
sudo systemctl start nginx
sudo systemctl enable nginx
- Open the Nginx configuration file
/etc/nginx/nginx.conf
in your text editor and add the following configuration to configure Nginx as a reverse proxy and load balancer:http {
upstream backend {
server 10.0.0.1;
server 10.0.0.2;
server 10.0.0.3;
}server {
listen 80;
location / {
proxy_pass http://backend;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}
}
In this configuration, the
upstream
block defines the backend servers that Nginx will load balance requests to. You can add or remove servers as needed. Theserver
block defines the virtual server that Nginx will use to receive incoming requests. Theproxy_pass
directive specifies the backend servers that Nginx will forward requests to. The otherproxy_set_header
directives are used to pass the original client’s IP address and other HTTP headers to the backend servers. - Test the configuration by running the following command:
sudo nginx -t
If the configuration is valid, Nginx will report that the configuration file test is successful.
- Reload the Nginx service by running the following command:
sudo systemctl reload nginx
This will load the new configuration and start using Nginx as a reverse proxy and load balancer.
You can now use Nginx to load balance incoming requests to your backend servers. If you need to add or remove backend servers, you can simply update the upstream
block in the Nginx configuration and reload the service.