SteelReed

Search

Search posts, questions…

6. DevOps & Operations

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.

18 Nov 20268 min readMid

–

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

NGINX
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 to server.request.header.forwarded.strategy=web-server), with server.tomcat.remoteip.internal-proxies matching the proxy's IP range. Without it, an app behind TLS termination builds http:// 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_pass both have or both lack the trailing /; no location /api without /.
  • Locations with their own proxy_set_header include the shared headers again.
  • The client IP comes from realip or right-to-left parsing, never the first X-Forwarded-For entry.
  • Keepalive has all three lines; SSE has buffering off; no retries for POST.
  • nginx -t runs in CI.

5. Exercises

Exercise 1: Read the config, predict the outcome

NGINX
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.png matches the /static/ prefix, but the \.png$ regex also matches and the regex wins: it's read from /var/cdn/static/logo.png. Fix with location ^~ /static/.
  • /api/v2/products matches location /api, and /api is replaced by /: the backend gets //v2/products. Fix with location /api/ (keep proxy_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 curl each request.

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 $scheme and Host $host; Spring Boot enables the forwarded strategy with internal-proxies matching Nginx's IP.
  • Check: call an endpoint through the proxy that returns getScheme() + getServerName(); you should see https and shop.vn. Add HSTS in Nginx.

Summary

  • location: = stops immediately, the longest prefix is kept, regexes beat prefixes unless ^~.
  • proxy_pass with a URI replaces the matched part; trailing / on both sides must agree.
  • proxy_set_header in a child location wipes the server headers.
  • Read the client IP from X-Forwarded-For right 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

All DevOps & Cloud questions →All System Design questions →

Loading comments…
Next on the roadmapThe Twelve-Factor App: 12 principles for cloud-ready services, applied to Spring Boot and Kubernetes