Reverse proxying with Nginx: path-based routing and X-Forwarded headers
Build an Nginx reverse proxy that routes /, /api and /blog to three services with Docker Compose and test every request: how location picks a block, the trailing-slash rule of proxy_pass, X-Forwarded headers and when to trust them, and production settings such as timeouts, keepalive, buffering and retries.
On this page
1. The problem
The config says location /api { proxy_pass http://be:8080/; }. The backend gets //orders for /api/orders, and /apiv2 reaches the backend as /v2. IP rate limiting reads the first X-Forwarded-For entry, so a client sending X-Forwarded-For: 6.6.6.6 gets around the limit.
2. Key idea
A reverse proxy is a building receptionist: visitors know one door, the receptionist reads the room name (path) and takes them to the right floor, and only trusts "where this visitor came from" notes written by the receptionist. A forward proxy sits on the client side; a load balancer is a reverse proxy spreading load across copies of one service; an API gateway adds token auth and per-client quotas.
Which location wins? Nginx remembers the longest matching prefix (declaration order doesn't matter); an exact location = /path match stops immediately; a prefix with ^~ skips regexes; otherwise the first matching regex in file order beats the prefix. Prefixes compare characters: location /api also matches /apiv2, so write location /api/.
What does proxy_pass do to the path?
| location | proxy_pass | Request | Backend receives |
|---|---|---|---|
/api/ |
http://backend (no URI) |
/api/orders |
/api/orders |
/blog/ |
http://blog:9000/ |
/blog/posts/1 |
/posts/1 |
/api |
http://be:8080/ |
/api/orders |
//orders |
/api |
http://be:8080/ |
/apiv2 |
/v2 |
The location and the proxy_pass URI must both have or both lack a trailing /.
2.1 Headers and whom to trust
Behind a proxy the backend loses the client IP, Host and scheme. Nginx sets Host $host, X-Real-IP $remote_addr, X-Forwarded-For $proxy_add_x_forwarded_for (appending, not replacing) and X-Forwarded-Proto $scheme. Anyone can forge the first X-Forwarded-For entry: trust the first IP from the right that isn't one of your proxies.
| Setup | Use when | Don't use when |
|---|---|---|
| Nginx (Caddy, HAProxy) | one entry point, path/host routing, TLS, per-IP rate limits | you need JWT checks, per-API-key quotas, route changes without reloads |
| API gateway (Kong, APISIX, Spring Cloud Gateway) | many teams, external clients needing auth and quotas | static routing is enough: one more system to run |
| Stripping prefixes at the proxy | services that don't know their prefix | services that generate their own links and redirects: the prefix gets lost |
3. Sample configuration
upstream backend { server be:8080; keepalive 32; }
server {
absolute_redirect off; # automatic redirects keep the port behind port mapping
include /etc/nginx/proxy_headers.conf; # Host, X-Real-IP, X-Forwarded-For/-Proto, X-Request-Id
location ^~ /api/ { # ^~: no regex can steal these requests
proxy_pass http://backend; # no URI: /api/... passes unchanged
proxy_http_version 1.1;
proxy_set_header Connection ""; # all three lines are needed for keepalive
proxy_connect_timeout 2s; proxy_read_timeout 30s;
include /etc/nginx/proxy_headers.conf; # this location sets its own headers: include again
}
location /blog/ { proxy_pass http://blog:9000/; } # strips the prefix; inherits server headers
location / { proxy_pass http://fe:8000; }
}proxy_set_header is only inherited when the current level has none of its own; add one line in a child location and every server-level header is gone.
Dangerous production defaults and the Spring Boot side
| Setting | Default | Problem | Do this |
|---|---|---|---|
| Timeouts | connect, read, send 60s | read is measured between two reads: a trickle keeps the connection forever | connect 1–2s, read per SLA |
| Upstream keepalive | none | a new TCP connection per request, ports exhausted by TIME_WAIT |
keepalive + HTTP/1.1 + Connection "" |
| Buffering | proxy_buffering on |
breaks SSE and streaming | proxy_buffering off; for that location |
| Retries | no retries for POST, PATCH |
enabling non_idempotent can create orders twice |
keep the default |
| Body size | client_max_body_size 1m |
a 3 MB upload gets 413, backend logs stay empty |
set it per location |
| Upstream DNS | resolved once when the config is read | 502 when a container gets a new IP | resolver + a variable in proxy_pass |
- realip:
set_real_ip_from 172.16.0.0/12; real_ip_header X-Forwarded-For; real_ip_recursive on;skips every trusted IP from the right. - Spring Boot must read the headers for
getRemoteAddr(),getScheme()and redirects to be right:server.forward-headers-strategy=native(renamed in Boot 4.2 toserver.request.header.forwarded.strategy=web-server), withserver.tomcat.remoteip.internal-proxiesmatching the proxy's IP range. Without it, an app behind TLS termination buildshttp://links and wrong OAuth2 redirect URIs.
4. Working with AI
Delegate to AI: Nginx config from a route table, a compose lab to try it, curl checks for every path.
Check yourself:
- Location and
proxy_passboth have or both lack the trailing/; nolocation /apiwithout/. - Locations with their own
proxy_set_headerinclude the shared headers again. - The client IP comes from realip or right-to-left parsing, never the first
X-Forwarded-Forentry. - Keepalive has all three lines; SSE has buffering off; no retries for
POST. -
nginx -truns in CI.
5. Exercises
Exercise 1: Read the config, predict the outcome
location /static/ { root /var/www; }
location ~* \.(png|jpg)$ { root /var/cdn; }
location /api { proxy_pass http://be:8080/; }Where do GET /static/logo.png and GET /api/v2/products go? AI says "static is read from /var/www, the API gets /api/v2/products". Right?
Solution to Exercise 1
/static/logo.pngmatches the/static/prefix, but the\.png$regex also matches and the regex wins: it's read from/var/cdn/static/logo.png. Fix withlocation ^~ /static/./api/v2/productsmatcheslocation /api, and/apiis replaced by/: the backend gets//v2/products. Fix withlocation /api/(keepproxy_pass http://be:8080/to strip the prefix, drop the trailing/to keep it).- Test: a compose lab with an echo server that returns the received path, then
curleach request.
Exercise 2: http:// links behind TLS
TLS ends at Nginx and Spring Boot runs plain HTTP behind it. After logging in, users are redirected to http://shop.vn/home and the browser warns. What's the cause and the fix?
Solution to Exercise 2
- Spring builds the redirect URL from
request.getScheme()=http, because it receives an HTTP connection from Nginx. - Fix both ends: Nginx sends
X-Forwarded-Proto $schemeandHost $host; Spring Boot enables the forwarded strategy withinternal-proxiesmatching Nginx's IP. - Check: call an endpoint through the proxy that returns
getScheme()+getServerName(); you should seehttpsandshop.vn. Add HSTS in Nginx.
Summary
location:=stops immediately, the longest prefix is kept, regexes beat prefixes unless^~.proxy_passwith a URI replaces the matched part; trailing/on both sides must agree.proxy_set_headerin a child location wipes theserverheaders.- Read the client IP from
X-Forwarded-Forright to left, trusting only your proxies. - Production: keepalive with all three lines, buffering off for SSE, no POST retries.
Further reading: Networking for backend engineers.
Practice interview questions on this topic
- How does a reverse proxy differ from a forward proxy? How does a backend behind a proxy get the real client IP and scheme?
- Why put Nginx in front of Spring Boot instead of exposing the application to the Internet directly?
- How does a load balancer work, and which balancing algorithms are there?
- How does an API gateway differ from a load balancer, and how do they work together?
Comments
Community rules