Reverse Proxy & Load Balancing
Nginx can act as a reverse proxy, forwarding client requests to backend servers.
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
|
Explanation of directives:
proxy_pass : Specifies the address of the backend server.
proxy_set_header : Sets HTTP headers to be passed to the backend server. It’s important to forward the original host, IP, and protocol information.
|
Nginx can distribute traffic across multiple backend servers using load balancing.
upsream backend {
server backend1.example.com;
server backend2.example.com;
}
server {
location / {
proxy_pass http://backend;
}
}
|
Different load balancing methods can be specified using the upstream block:
round-robin (default): Distributes requests in a round-robin fashion.
ip_hash : Distributes requests based on the client’s IP address.
least_conn : Sends requests to the server with the fewest active connections.
|