DEVOPS, SRE AND CLOUD · PART 2 · NETWORKING FOR DEVOPS · TRAFFIC · 40 OF 187

Nginx Reverse Proxy: Config, TLS and Caching

Configure nginx the way production uses it, tested in front of ShopRung: server and location blocks, proxy_pass with the right headers and upstream keep-alive, TLS termination with an HTTP to HTTPS 301, caching (MISS in 1.8 ms, then HIT in 0.3 ms), gzip (1,668 bytes down to 568), rate limiting (20 fast requests: 6 passed, 14 got 429), timeouts, nginx -t, reload and the logs.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
1 / 12

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • proxy_pass + headers
  • keep-alive
  • 301 to HTTPS
  • cache HIT 0.3 ms
  • gzip 1,668 → 568
  • 429s
  • nginx -t

Notes

Why a proxy

Why put a proxy in front at all? nginx terminates TLS, so the app speaks plain HTTP on localhost. One port can serve many apps by host name or path. Its event loop absorbs slow clients so your app's workers are not tied up. It caches, compresses, rate limits, serves static files and writes consistent access logs. The application focuses on business logic.

nginx in front gives
  • TLS termination
  • one port for many apps (by host or path)
  • slow clients handled by an event loop, not app threads
  • caching, compression
  • rate limits, IP rules
  • static files, fast
  • access logs in one place

The core config

The core config. An upstream block names the backend and keeps up to sixteen idle connections open to it. A server block listens on a port and matches a server name. A location block matches paths and proxy_pass sends requests upstream. Two easy to miss lines: proxy http version one point one and an empty Connection header, without which upstream keep alive does not work. And set Host and X-Forwarded-For, so the app sees the real host and client address.

nginx.conf (ours)
upstream shoprung {
  server 127.0.0.1:8080;
  keepalive 16; }
server { listen 8443 ssl
    http2; server_name
    shoprung.test;
 location / {
  proxy_pass http://shoprung;
  proxy_http_version 1.1;
  proxy_set_header Connection
    ""; ...Host, X-Forwarded

TLS and redirect

TLS termination uses the certificate and key from the last episodes, with only TLS one point two and 1.3 allowed. A small second server block catches plain HTTP and returns a permanent redirect. Our request to the HTTP port got 301 pointing at the same path on HTTPS. Keeping the path in the redirect, with the request URI variable, matters for both users and search engines.

Our test
server { listen 8081;
  return 301 https://
    shoprung.test:8443
    $request_uri; }

$ curl :8081/api/health
301 → https://shoprung.test
  :8443/api/health
ssl_protocols TLSv1.2 TLSv1.3

Caching

Caching. We cached the product list for thirty seconds and added a header showing the cache status. The first request was a MISS, went to ShopRung, and took one point eight milliseconds. The next two were HITs served from nginx's cache in about a quarter of a millisecond, without touching the app at all. Only cache responses that are the same for everyone: product lists yes, a user's cart never.

/api/products, 3 requests
X-Cache: MISS  1.843 ms
X-Cache: HIT   0.315 ms
X-Cache: HIT   0.251 ms

proxy_cache_path ... keys_
  zone=shop:10m;
proxy_cache shop;
proxy_cache_valid 200 30s;
never cache per-user pages

Compression

Compression. The product list was one thousand six hundred and sixty eight bytes. With a client that accepts gzip, nginx sent five hundred and sixty eight, about a third. nginx only compresses the types you list, so add application slash json for APIs, and skip tiny responses and images, which are already compressed.

Same JSON (ours)
without Accept-Encoding:
  1,668 bytes
Accept-Encoding: gzip:
    568 bytes

gzip on;
gzip_types application/json;
gzip_min_length 256;
skip images, already small

Rate limiting

Rate limiting. We allowed five requests a second per client address, with a burst of five. Twenty requests fired as fast as possible: six succeeded, the first one plus the burst, and fourteen got four two nine, too many requests. nginx tracks clients in a small shared memory zone. Behind another load balancer, limit by the real client address, or every user shares one bucket.

20 quick requests (ours)
limit_req_zone
  $binary_remote_addr
  zone=perip:1m rate=5r/s;
limit_req zone=perip
  burst=5 nodelay;
limit_req_status 429;

6 × 200
14 × 429 Too Many Requests

Change it safely

Change nginx safely. nginx minus t checks the configuration before you apply it; ours once failed with unknown directive http two, because the directive came in a newer version. A reload starts new workers with the new config while old workers finish their requests, so nothing drops. nginx minus T prints the full merged config. And the access log shows every request, while the error log explains every five oh two.

Every change
$ nginx -t
  syntax is ok / test is
  successful
$ nginx -s reload
  (or systemctl reload nginx)
  old workers finish, new
  ones start: no downtime
$ nginx -T   full config
access.log, error.log

Timeouts and limits

Some defaults bite. proxy read timeout is sixty seconds, so a slow report endpoint returns five oh four. client max body size is one megabyte, so uploads fail with four thirteen. Response buffering is on, which breaks server sent events and streaming until you turn it off for that location. And websockets need the Upgrade and Connection headers passed through. Set each deliberately per location.

Know these
  • proxy_read_timeout 60s → 504 for slow endpoints
  • proxy_connect_timeout
  • client_max_body_size 1m → 413 on big uploads
  • proxy_buffering (on): off for streaming/SSE
  • websockets: Upgrade and Connection headers

Common mistakes

Mistakes. Reloading without nginx minus t. No keep alive to the upstream. Losing the client's address because X-Forwarded-For is not set. Caching responses that differ per user. A trailing slash in proxy_pass, which silently rewrites paths. Forgetting the one megabyte upload limit. And no rate limit on login endpoints.

Avoid these
  • reload without nginx -t
  • no upstream keep-alive
  • missing X-Forwarded-For
  • caching per-user responses
  • proxy_pass trailing slash surprises (path rewrite)
  • default 1 MB upload limit
  • no rate limit on login

Say it like this

In the interview: a reverse proxy accepts client connections and forwards requests to backends, so it can terminate TLS, route by host and path, balance load, cache, compress, rate limit and log in one place. With nginx I keep upstream connections alive, pass the forwarded headers, test with nginx minus t, reload without downtime, and set timeouts and body limits per location.

In the interview
  • "It accepts client connections
  • and forwards requests to backends: TLS termination, routing by host and path, load
  • balancing, caching, gzip, rate
  • limits and logging. With nginx I
  • test with nginx -t, reload with no downtime, tune timeouts."

Interview questions

Q1What is the difference between a forward proxy and a reverse proxy?

A forward proxy acts for clients reaching the internet; a reverse proxy sits in front of servers and receives requests on their behalf.

Q2How do you reload nginx without downtime?

Run nginx -t to validate, then nginx -s reload or systemctl reload nginx: new workers start with the new config while old ones finish their requests.

Q3Why set proxy_http_version 1.1 and an empty Connection header?

They allow nginx to reuse keep-alive connections to the upstream defined with keepalive, instead of opening a new connection per request.

Q4How do you get the client IP in an app behind nginx?

Set proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for (and X-Real-IP), and have the app trust only the proxy's address for that header.

Q5Why does nginx return 413 or 504?

413: the request body exceeded client_max_body_size. 504: the upstream did not respond within proxy_read_timeout.

Q6How does nginx rate limiting work?

limit_req_zone defines a key (like client IP) and rate in shared memory; limit_req applies it with an optional burst; excess requests get 503 or a set status like 429.

Q7What should and should not be cached at the proxy?

Cache public, identical-for-everyone responses (product lists, static assets); never cache personalised or authenticated responses without a per-user key.