Nginx handles millions of concurrent connections efficiently, making it the ideal reverse proxy and load balancer for production applications. This guide covers real-world configurations.
Basic Reverse Proxy
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
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;
# Timeouts
proxy_connect_timeout 60s;
proxy_send_timeout 60s;
proxy_read_timeout 60s;
}
}
Load Balancing with Health Checks
upstream backend {
least_conn; # or: round_robin, ip_hash, hash $request_uri
server 10.0.0.1:3000 weight=3 max_fails=3 fail_timeout=30s;
server 10.0.0.2:3000 weight=2 max_fails=3 fail_timeout=30s;
server 10.0.0.3:3000 backup; # Only used when others are down
}
server {
listen 443 ssl http2;
server_name app.example.com;
ssl_certificate /etc/letsencrypt/live/app.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/app.example.com/privkey.pem;
location / {
proxy_pass http://backend;
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 3;
}
}
WebSocket Proxy
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s;
proxy_send_timeout 86400s;
}
Caching Proxy
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=app_cache:10m
max_size=1g inactive=60m use_temp_path=off;
server {
location /api/ {
proxy_pass http://backend;
proxy_cache app_cache;
proxy_cache_valid 200 10m;
proxy_cache_valid 404 1m;
proxy_cache_key "$scheme$request_method$host$request_uri";
add_header X-Cache-Status $upstream_cache_status;
}
}
π Master Nginx Configuration
Our Nginx eBook covers everything from basic setup to advanced load balancing, security hardening, and performance optimization.
Browse All Books βNginx as a reverse proxy handles SSL termination, load balancing, caching, and WebSocket connections β all while using minimal resources. Start with the basics and add complexity as your infrastructure grows.