Sub topic 9
Reverse proxying to an application server
A reverse proxy is a server that accepts client requests and forwards them to another server, then returns the response to the client. Nginx is often placed in front of an application server such as Node.js, Gunicorn, or a Java service. Nginx handles the public connection, and the application handles the business logic.
This chapter assumes you can edit Nginx configuration with sudo, know how server blocks and location blocks work, and understand HTTP headers and TCP ports. It also assumes you can test and reload configuration with nginx -t and systemctl reload nginx.
Why put Nginx in front of an application
An application server is usually good at running application code. It is often weaker at handling slow clients, TLS, static files, and many idle connections. Nginx covers these jobs well.
- TLS termination. Nginx handles HTTPS, and the application can listen on plain HTTP on a local port.
- Single public entry point. Only ports 80 and 443 are open. The application port can be bound to
127.0.0.1and stay unreachable from outside. - Buffering. Nginx reads the whole response from the application quickly, then sends it to a slow client. This frees the application worker sooner.
- Routing. Different URL paths can go to different applications or to static files.
- Shared features. Logging, rate limiting, compression, and load balancing apply to every backend in one place.
The request flow looks like this.
The basic proxy_pass setup
The proxy_pass directive sends a request to another server. It is valid in location blocks (and if inside a location, and limit_except). The following block forwards everything under /api/ to an application on local port 3000.
location /api/ {
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;
}To try this, start any application on port 3000. Python's built-in server works for a quick check:
mkdir -p /tmp/demo && cd /tmp/demo
echo "hello from the backend" > index.html
python3 -m http.server 3000 --bind 127.0.0.1Then test the configuration, reload, and request the path through Nginx from another terminal:
sudo nginx -t && sudo systemctl reload nginx
curl -i http://localhost/api/The response comes from the Python server, not from Nginx. Note that the Python server will look for /api/index.html here, because of how URIs are passed (explained next). A 404 from the backend still proves the proxy path works. A 502 from Nginx means the proxy failed to reach the backend.
How the URI is passed to the backend
The rule depends on whether proxy_pass contains a URI part, meaning anything after the host and port, including a bare /.
- Without a URI (
proxy_pass http://127.0.0.1:3000;), Nginx passes the original request URI unchanged. - With a URI (
proxy_pass http://127.0.0.1:3000/;), Nginx replaces the part of the request that matched the location prefix with that URI.
| Location | proxy_pass | Request | Backend receives |
|---|---|---|---|
| `/api/` | `http://127.0.0.1:3000` | `/api/users` | `/api/users` |
| `/api/` | `http://127.0.0.1:3000/` | `/api/users` | `/users` |
| `/api/` | `http://127.0.0.1:3000/v2/` | `/api/users` | `/v2/users` |
A single trailing slash is a common source of 404 errors from the backend. Decide whether the application expects the /api/ prefix, then choose the form that matches.
Two more edge cases apply:
- If the location uses a regular expression,
proxy_passcannot contain a URI part. Nginx will refuse the configuration. - If
proxy_passuses variables, Nginx does not do the prefix replacement described above. It uses the URI exactly as written in the directive. It also resolves host names at request time, which needs aresolverdirective.
Passing the original client information
By default, the backend sees Nginx as the client. Nginx also rewrites the Host header to the proxy_pass host and port, such as 127.0.0.1:3000. Applications that build absolute URLs, set cookies per domain, or log client addresses then behave incorrectly. The four proxy_set_header lines fix this.
| Header | Value | Purpose |
|---|---|---|
| `Host` | `$host` | The host name the client requested |
| `X-Real-IP` | `$remote_addr` | The client's IP address |
| `X-Forwarded-For` | `$proxy_add_x_forwarded_for` | The client IP appended to any existing chain of proxies |
| `X-Forwarded-Proto` | `$scheme` | `http` or `https`, so the app knows the original protocol |
These are conventions, not guarantees. The application must be configured to read them. Most frameworks have a "trusted proxy" setting for this. Trust these headers only when the request came from your own Nginx. If the application is reachable directly from the internet, a client can forge them.
$host and $http_host differ. $host is normalized: lowercase, without the port, and falls back to the server_name if the header is missing. $http_host is the raw header, including any port.
Because the same headers are usually needed in many locations, a common practice is to put them in a file such as /etc/nginx/snippets/proxy-headers.conf and add include snippets/proxy-headers.conf; where needed. Note that proxy_set_header follows inheritance rules: if a location defines any proxy_set_header, it does not inherit the ones from the enclosing server block. Define them all at one level.
Timeouts, buffering, and errors
The defaults are reasonable for most applications. These are the settings you will most often adjust.
| Directive | Default | Meaning |
|---|---|---|
| `proxy_connect_timeout` | 60s | Time allowed to establish a connection to the backend |
| `proxy_send_timeout` | 60s | Maximum gap between two writes to the backend |
| `proxy_read_timeout` | 60s | Maximum gap between two reads from the backend |
| `proxy_buffering` | on | Read the backend response into buffers before sending |
| `client_max_body_size` | 1m | Largest request body accepted from a client |
Typical adjustments look like this:
location /api/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Connection "";
proxy_connect_timeout 5s;
proxy_read_timeout 120s;
client_max_body_size 20m;
}Notes on these settings:
- A short
proxy_connect_timeoutmakes failures fast when the backend is down. A longproxy_read_timeoutis useful for slow reports or exports. client_max_body_sizeis a frequent cause of413 Request Entity Too Largewhen users upload files. The limit is enforced by Nginx before the request reaches the application.proxy_http_version 1.1with an emptyConnectionheader is needed for keep-alive connections to anupstreamgroup that uses thekeepalivedirective. Without it, Nginx talks HTTP/1.0 to the backend and opens a new connection for each request.- Turn
proxy_buffering offonly for streaming responses such as server-sent events. With buffering off, a slow client holds an application worker for the whole transfer.
WebSocket connections
WebSocket starts as an HTTP request that asks to upgrade the connection. Nginx does not forward the Upgrade and Connection hop-by-hop headers unless you tell it to.
http {
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name example.com;
location /ws/ {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;
proxy_read_timeout 3600s;
}
}
}The map block must sit in the http context, outside any server. It sets Connection to upgrade for WebSocket requests and close for normal ones. The long proxy_read_timeout matters because an idle WebSocket would otherwise be closed after 60 seconds.
Common errors
The status code Nginx returns tells you where to look.
| Status | Typical cause | First check |
|---|---|---|
| 502 Bad Gateway | The backend is down, refused the connection, or sent an invalid reply | Is the app running, and on the port named in `proxy_pass`? |
| 504 Gateway Timeout | The backend did not answer within the read timeout | Slow application code, or raise `proxy_read_timeout` |
| 413 Request Entity Too Large | The request body exceeds `client_max_body_size` | Raise the limit in the right context |
| 404 from the backend | A URI mismatch caused by the trailing slash | Compare `location` and `proxy_pass` URIs |
| Wrong redirects or `http://` links | The app does not know the original scheme or host | Pass `X-Forwarded-Proto` and `Host`, and configure the app to trust them |
A 502 is the most common. Check it step by step:
curl -i http://127.0.0.1:3000/
sudo ss -ltnp | grep 3000
sudo tail -n 20 /var/log/nginx/error.logThe first command tests the backend directly, bypassing Nginx. The second shows whether anything is listening on port 3000. The third shows the exact error, for example connect() failed (111: Connection refused).
On distributions with SELinux enabled, such as RHEL and Fedora, a 502 with Permission denied in the error log usually means SELinux blocks Nginx from making network connections. The fix is sudo setsebool -P httpd_can_network_connect 1. Debian and Ubuntu do not enable SELinux by default.
Summary of working rules
- Bind the application to
127.0.0.1and proxy to it. - Always set
Hostand theX-Forwarded-*headers, and configure the application to trust them from Nginx only. - Check the trailing slash on
proxy_passagainst the location prefix. - Use HTTP 1.1 and an empty
Connectionheader for keep-alive, and themappattern for WebSocket. - Read the status code and
error.logtogether to locate failures.
Exercise
A location block is location /api/ { proxy_pass http://127.0.0.1:3000/; }. A client requests /api/orders/7. What path does the backend receive, and what single change makes it receive /api/orders/7 instead?
Show answer
The backend receives /orders/7, because proxy_pass contains a URI part (the trailing /), so Nginx replaces the matched prefix /api/ with /. Removing the trailing slash, so the directive reads proxy_pass http://127.0.0.1:3000;, passes the original URI unchanged.
Exercise
Users report that file uploads of 5 MB fail with a 413 error, while the application's own limit is 50 MB. Which directive is responsible, what is its default, and how do you apply a fix safely?
Show answer
client_max_body_size is responsible. Its default is 1m, and Nginx enforces it before the request reaches the application. Set it to a larger value, for example client_max_body_size 50m;, in the http, server, or location context. Then run sudo nginx -t && sudo systemctl reload nginx.
Exercise
A request through Nginx returns 502 Bad Gateway. List three commands you would run and what each tells you.
Show answer
curl -i http://127.0.0.1:3000/ tests the backend directly and shows whether it answers. sudo ss -ltnp | grep 3000 shows whether a process listens on the expected port. sudo tail -n 20 /var/log/nginx/error.log shows the exact error, such as connection refused or permission denied.