Basic Reverse Proxy
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:3000;
}
}
location / {
proxy_pass http://localhost:3000;
# Pass original host
proxy_set_header Host $host;
# Pass real client IP
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# Pass protocol (http/https)
proxy_set_header X-Forwarded-Proto $scheme;
# HTTP version
proxy_http_version 1.1;
# Connection upgrade (for WebSocket)
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Proxy Path Handling
# Trailing slash matters!
# /api/users -> backend:/users
location /api/ {
proxy_pass http://localhost:3000/;
}
# /api/users -> backend:/api/users
location /api/ {
proxy_pass http://localhost:3000;
}
Timeouts
location / {
proxy_pass http://localhost:3000;
# Connection timeout
proxy_connect_timeout 60s;
# Read timeout
proxy_read_timeout 60s;
# Send timeout
proxy_send_timeout 60s;
}
Buffering
location / {
proxy_pass http://localhost:3000;
# Enable buffering (default)
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# Disable buffering (for streaming)
# proxy_buffering off;
}
Error Handling
location / {
proxy_pass http://localhost:3000;
# Intercept backend errors
proxy_intercept_errors on;
# Custom error pages
error_page 502 503 504 /50x.html;
}
location = /50x.html {
root /var/www/html;
internal;
}
Complete Example
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
# Headers
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;
# WebSocket support
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
# Timeouts
proxy_connect_timeout 60s;
proxy_read_timeout 60s;
# Buffering
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}
intermediate | Reverse Proxy | Updated 2025-01-15
- nginx
- reverse proxy
- proxy_pass
- backend
- headers