Nginx Config by Example: Reverse Proxy
Forwarding requests to backend servers with this sample code demonstrating proxy_pass directive for upstream forwarding, proxy_set_header for client information preservation, timeout configuration, and buffer settings for response handling.
Code
server {
listen 80;
server_name app.example.com;
location / {
# Forward requests to the backend server
proxy_pass http://localhost:3000;
# Pass headers to the backend
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_read_timeout 60s;
# Buffer settings
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
}
}Explanation
Nginx functions as a reverse proxy by sitting in front of web servers and forwarding client requests to backend application servers like Node.js, Python, Go, or PHP-FPM. The proxy_pass directive specifies the upstream server URL where requests should be forwarded, which can be an IP address and port, a Unix domain socket, or an upstream group name. Nginx handles the client connection, forwards the request, receives the backend response, and sends it back to the client.
The proxy_set_header directive preserves original client information when forwarding requests. Without these headers, backend applications see requests originating from Nginx's localhost address rather than the actual client. The Host header maintains the original domain name, X-Real-IP contains the client's IP address, X-Forwarded-For tracks the request path through proxies, and X-Forwarded-Proto indicates whether the original request used HTTP or HTTPS.
Timeout directives control connection behavior with proxy_connect_timeout limiting backend connection establishment time and proxy_read_timeout setting the maximum time to receive a response. Buffer settings determine how Nginx handles backend responses: proxy_buffering on enables response buffering, proxy_buffer_size sets the buffer for response headers, and proxy_buffers defines the number and size of buffers for the response body. Buffering allows Nginx to free backend processes quickly by reading the entire response before sending to clients.
Code Breakdown
proxy_pass http://localhost:3000 forwards requests to backend server.proxy_set_header directives preserve original client information for backend.
