Nginx Reverse Proxy Setup
Learn how to configure Nginx as a reverse proxy server to forward client requests to backend application servers. Complete step-by-step setup guide.
Detailed Explanation
A reverse proxy sits between clients and your backend servers, forwarding requests on behalf of the client. Nginx excels in this role due to its event-driven architecture and low memory footprint.
Basic Configuration
The core directive is proxy_pass, which tells Nginx where to forward incoming requests. You place this inside a location block within your server block.
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://127.0.0.1:3000;
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;
}
}
Important Headers
When proxying, the backend application loses visibility into the original client connection. The proxy_set_header directives solve this by passing along the original host, IP address, and protocol. Without these headers, your backend would see all requests as originating from the local loopback address 127.0.0.1, making it impossible to log real client IPs or enforce IP-based security rules.
The X-Forwarded-For header builds a chain of all proxies the request has traversed. The X-Forwarded-Proto header preserves the original protocol so your application can correctly generate absolute URLs and enforce HTTPS redirects even when SSL terminates at the Nginx layer.
Buffering and Timeouts
Nginx buffers responses from the backend by default, which improves performance for slow clients. You can tune this behavior with proxy_buffering, proxy_buffer_size, and proxy_buffers. Timeout directives like proxy_connect_timeout, proxy_read_timeout, and proxy_send_timeout prevent connections from hanging indefinitely. Setting these values appropriately is critical for both user experience and resource management on the server.
Error Handling
Use proxy_intercept_errors on combined with error_page directives to serve custom error pages when your backend returns 5xx errors. This provides a better user experience during outages and prevents leaking internal stack traces or debugging information to end users.
Best Practices
- Always set the
Hostheader so the backend knows which virtual host was requested. - Use
X-Forwarded-Prototo let the backend detect HTTPS even when SSL terminates at Nginx. - Consider adding
proxy_next_upstreamto automatically retry failed requests on another backend server. - Set reasonable timeouts to prevent idle connections from consuming server resources.
- Monitor upstream response times using the
$upstream_response_timelog variable to identify slow backends before they affect end users.
Use Case
You are deploying a Node.js or Python web application behind Nginx to handle SSL termination, serve static assets efficiently, and add a layer of protection against direct backend exposure.