How to Proxy Multiple Backends in Nginx: Simple Guide
To proxy multiple backends in
nginx, define separate location blocks for each backend or use an upstream block to group servers. Then use proxy_pass inside each location to forward requests to the correct backend.Syntax
Use location blocks to match request paths and proxy_pass to forward requests to backend servers. Optionally, group multiple backends with upstream for load balancing.
location /path/ { proxy_pass http://backend; }: forwards requests matching/path/tobackend.upstream backend { server backend1; server backend2; }: defines a group of backend servers.
nginx
http {
upstream backend_group {
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
location /app1/ {
proxy_pass http://backend1.example.com/;
}
location /app2/ {
proxy_pass http://backend2.example.com/;
}
location /appgroup/ {
proxy_pass http://backend_group;
}
}
}Example
This example shows how to proxy requests to two different backends based on URL path, and how to use an upstream group for load balancing multiple servers.
nginx
http {
upstream backend_servers {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
}
server {
listen 80;
location /service1/ {
proxy_pass http://192.168.1.20:5000/;
}
location /service2/ {
proxy_pass http://192.168.1.21:6000/;
}
location /loadbalanced/ {
proxy_pass http://backend_servers;
}
}
}Output
Nginx listens on port 80 and forwards requests:
- /service1/ to 192.168.1.20:5000
- /service2/ to 192.168.1.21:6000
- /loadbalanced/ to either 192.168.1.10:8080 or 192.168.1.11:8080 (load balanced)
Common Pitfalls
- Forgetting the trailing slash in
proxy_passcan cause incorrect URL forwarding. - Not defining
upstreamblocks properly leads to load balancing failure. - Overlapping
locationblocks can cause unexpected routing. - Missing
proxy_set_header Host $host;can break backend host header expectations.
nginx
server {
listen 80;
# Wrong: missing trailing slash causes wrong URL forwarding
location /app/ {
proxy_pass http://backend.com;
}
# Correct: trailing slash preserves path
location /app/ {
proxy_pass http://backend.com/;
}
}Quick Reference
| Directive | Purpose | Example |
|---|---|---|
| location | Matches request URI path | location /api/ { ... } |
| proxy_pass | Forwards request to backend | proxy_pass http://backend; |
| upstream | Defines backend server group | upstream backend { server 1.1.1.1; server 2.2.2.2; } |
| proxy_set_header | Sets headers sent to backend | proxy_set_header Host $host; |
Key Takeaways
Use separate location blocks with proxy_pass to route to different backends.
Group multiple backend servers with upstream for load balancing.
Always include trailing slash in proxy_pass URL to preserve request paths.
Set proper headers like Host to ensure backend compatibility.
Avoid overlapping location blocks to prevent routing conflicts.