Nginx as a Reverse Proxy: Complete Setup
A no-nonsense Nginx reverse proxy configuration with SSL and common headers.
Key Insights
- Always redirect HTTP to HTTPS and set security headers (X-Frame-Options, X-Content-Type-Options, Referrer-Policy)
- WebSocket proxying requires explicit HTTP/1.1 upgrade headers — it won’t work with the default proxy config
- Rate limiting at the reverse proxy layer protects your application without adding complexity to your code
Every web application eventually needs a reverse proxy. Nginx remains the best choice for most setups — it’s fast, stable, and well-documented.
Basic Reverse Proxy
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl http2;
server_name example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:8080;
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;
}
}
Essential Headers
Always set these security headers:
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
WebSocket Support
location /ws {
proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
Rate Limiting
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
proxy_pass http://127.0.0.1:8080;
}
This covers the majority of reverse proxy use cases. For anything more complex, consider whether you actually need it.