This resume is also available in English.

8. Security and working with AI3 / 12 · All columns

Columns › 8. Security and working with AI › Part 49

Go Behind nginx: Security Settings and API Reverse Proxy Configuration

Go 搭配 nginx:安全設定與 API 反向代理怎麼配

Put nginx in front of Go services to handle TLS, rate limits, request sizes and slow clients while Go focuses on business logic. Starting from what a reverse proxy is, this article configures upstreams, proxy_pass, timeouts, security headers, rate limiting and the real client IP step by step, and writes a Go middleware that only trusts known proxies; every behaviour was tested in containers.

  • nginx
  • Go
  • Security
  • Reverse Proxy
In this article
  1. What this article solves
  2. Step 1: What a reverse proxy is, and why put one in front of Go
  3. Step 2: How one request travels through the nginx configuration
  4. Step 3: upstream, the keepalive pool, and the headers Go needs
  5. Step 4: The slash in proxy_pass decides what the path looks like
  6. Step 5: Align timeouts, request sizes, buffering and retries with Go
  7. Step 6: Security settings at the nginx layer
  8. Step 7: Rate limiting with a leaky bucket — rate, burst and nodelay
  9. Step 8: Why the client IP disappears, and how to read X-Forwarded-For
  10. Step 9: Server settings on the Go side
  11. Step 10: Logs, the complete configuration and the rollout procedure
  12. Step 11: What belongs in nginx and what belongs in Go
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Field-Level Encryption in the Database: How to Encrypt, and How to Query Encrypted Data”, encrypted the personal data in the database, protecting the end where data is stored. This article returns to the end where requests come in: before traffic reaches the shop's api-gateway, written in Go, it usually passes through an nginx server. Configured well, this layer stops many attacks before they ever touch Go; configured badly, it quietly breaks rate limiting, lets clients forge their own IP address, or drops security headers on some paths without anyone noticing.

What this article solves

“Building an API Gateway in Go: Routing, Authentication and Rate Limiting” wrote a gateway in Go that handles routing, JWT authentication and per-user rate limiting, and “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain” covered authentication, authorisation and mTLS. In production, though, something still has to sit in front of api-gateway and deal with HTTPS certificates, redirecting HTTP to HTTPS, the front end's static files, oversized requests, clients on very slow networks and scripts firing a thousand requests a second from one IP. None of this is business logic, and nginx does it maturely and cheaply.

The trouble is that nginx configuration looks simple but contains a fair number of things that look right and are wrong. Using the shop system (example.com/shop) as the example, this article starts from the concepts and builds a complete configuration step by step:

  1. What a reverse proxy is, what TLS termination means, and when to put nginx in front of Go and when not to.
  2. How one request travels through server, location and upstream to reach Go, and which directives act at each step.
  3. upstream and the keepalive connection pool, and the headers to pass to Go.
  4. What the path becomes with and without a trailing slash on proxy_pass.
  5. How to align nginx and Go timeouts, request sizes, buffering and retries; proxying WebSocket and gRPC.
  6. Security at the nginx layer: TLS, security headers, the add_header inheritance trap, unknown Hosts and dotfiles.
  7. Rate limiting with a leaky bucket: what rate, burst and nodelay mean.
  8. Why the client IP disappears behind proxies and how to read X-Forwarded-For without being fooled; a realip middleware in Go.
  9. Server settings on the Go side, letting only nginx reach Go, and shutting down in step with nginx.
  10. JSON access logs, the complete configuration file and the rollout procedure.
  11. What belongs in nginx, what in Go and what in the API gateway.

The nginx configuration follows the official nginx.org documentation and was run in containers using the official nginx:stable image (1.30.7): one container played the CDN, one a client connecting directly, and the Go program from this article sat behind nginx. Every output quoted below is what those tests actually produced.

Step 1: What a reverse proxy is, and why put one in front of Go

First, tell the two kinds of proxy apart. A forward proxy sits on the client side: computers on a company network reach the internet through it, and outside websites see the proxy, not the employee's machine. It hides and controls clients. A reverse proxy sits on the server side: users on the internet think they are talking to shop.example.com, but an nginx server receives the request and passes it to the Go services behind it. It stands in front of servers.

Forward proxy Reverse proxy (nginx here) Client 1 Client 2 Client 3 Proxy office exit Site external Goes out for clients; sites see only the proxy User nginx entry api-gateway order payment Receives for servers; clients know only nginx The software may be the same; what differs is which side it stands on and whom it works for

Figure: a forward proxy goes out on behalf of a group of clients; a reverse proxy receives incoming requests on behalf of a group of servers, and clients only know the proxy's address.

A reverse proxy can do many things, but for Go services these are the reasons that actually justify an nginx server:

ReasonWhat it doesWhy not do it in Go
TLS terminationDecrypts HTTPS at nginx, so certificates live in one placeGo can do it, but then every service manages certificates and renewal
Buffering slow clientsnginx receives the whole request body before handing it to Go in one go, and buffers responses tooGo's goroutines need not keep pace with a phone on a weak signal
Static filesFront-end HTML, JavaScript and images are served directly by nginxStatic files should not use application resources
Coarse rate and size limitsRate limits by IP, caps body size, rejects unknown HostsStopping requests before they reach the application is cheapest
Single entry pointSeveral services share one domain and certificate, split by pathOnly one port is exposed

Another term that comes up constantly is TLS termination. The connection from client to nginx is encrypted HTTPS; nginx unwraps TLS there and sees the full HTTP request, which is what lets it route by path, add headers and apply rate limits. For the hop from nginx to Go there are two choices: plain HTTP on the same machine or a trusted private network, or encrypting again (even with mTLS, so each side verifies the other).

Client CDN nginx terminates TLS api-gateway Go Services HTTPS HTTPS HTTP or mTLS Encrypted (HTTPS) Private network: plain or re-encrypted Sees plaintext Sees plaintext Every place that terminates TLS sees the request; keep tokens and bodies out of logs

Figure: client to CDN and CDN to nginx are HTTPS; nginx terminates TLS and forwards to Go over a plain or re-encrypted connection. Every place that terminates TLS can see the request contents.

Note what "unwraps" means: every place that terminates TLS sees plaintext, the CDN included. That is why the logging configuration later deliberately leaves out the Authorization header and request bodies.

When you do not need nginx. This layer is not mandatory. Judge it like this:

  • Go can serve HTTPS itself. net/http's ListenAndServeTLS, with sensible http.Server timeouts, can face the internet directly. With one service, no static files and no path-based routing, an extra nginx is just one more component to patch and monitor.
  • Inside Kubernetes there is already an Ingress controller or a Gateway API implementation (“Deploying a Microservice System on Kubernetes”). Those are reverse proxies already; putting an nginx in front of each Pod as well means two layers doing the same job.
  • Avoid two layers doing the same job. If nginx and the Go gateway both rate-limit, both add security headers and both rewrite paths, it becomes hard to tell which layer caused a problem. Each section below states which layer a job belongs to.

The scenario in this article: the shop runs on a few virtual machines, or in an environment like “Deploying a Whole Microservice System with Docker Compose”, with a CDN in front. nginx is the public entry point; behind it is api-gateway (Go), and behind that order, payment and inventory. On Kubernetes, the same principles map onto the Ingress controller's settings.

Step 2: How one request travels through the nginx configuration

nginx configuration is blocks nested inside blocks. Before reading a configuration, look at the decisions nginx makes, in order, when a request arrives:

① server listen 443 ssl; server_name shop.example.com Chosen by port and Host (SNI) No match → default_server returns 444 ② location /api/ longest prefix; regexes in order Chosen by the request path Path /api/orders/42 lands here ③ limit_req · proxy_set_header proxy_read_timeout · proxy_pass Rate limit, add headers, timeouts proxy_pass http://api_gateway ④ upstream api_gateway server 10.0.1.21:8080; keepalive 32; Takes an idle pooled connection Opens one if none; retries per next_upstream api-gateway (Go) realip middleware · http.Server timeouts Accepts connections only from nginx Then on to order, payment, inventory Each step reads only its own level; inheritance rules differ between directives

Figure: ① choose a server block by port and Host; ② choose a location by path; ③ the location's rate limits, headers and timeouts apply, and proxy_pass points at an upstream; ④ the upstream takes a connection from its pool and sends the request to Go.

  1. Choose a server: nginx looks at which IP address and port the request arrived on, then matches Host (the TLS SNI for HTTPS) against server_name. If nothing matches, the request goes to that port's default server: the one marked default_server, or, failing that, the first one in the configuration.
  2. Choose a location: within the chosen server, the request path is matched against location blocks. Among prefix matches the longest wins; regular expressions are tried in order of appearance and the first match is used.
  3. Run the location's directives: rate limits, headers, timeouts and proxy_pass.
  4. The upstream picks a backend: it takes an idle connection from the pool (or opens one) and sends the request to Go.

Step 1 hides a security issue: unless you handle it explicitly, a scanner connecting by bare IP, or with any Host it likes, lands on "the first server", which is your real site. The fix is an explicit default server that does nothing:

# Unknown Host: drop the connection, send nothing
server {
    listen 80  default_server;
    listen 443 ssl default_server;
    ssl_reject_handshake on;   # since 1.19.4; HTTPS is rejected during the handshake
    return 444;                # nginx-specific: no response, just close the connection
}

# Port 80 only redirects
server {
    listen 80;
    server_name shop.example.com;
    return 301 https://$host$request_uri;
}

Test results: connecting to port 80 by IP, curl gets curl: (52) Empty reply from server; on port 443 the TLS handshake itself fails (tlsv1 unrecognized name), so no certificate is ever sent and a scanner cannot learn your domain from it. ssl_reject_handshake means this default server needs no certificate at all.

Fits: every public-facing nginx should have this default server. Why: it blocks Host header attacks (for example, using a wrong Host to generate password-reset links) and bulk indiscriminate scanning. Does not fit: if a CDN sits in front of nginx and does not forward SNI or rewrites Host, check the CDN's behaviour first, or legitimate traffic will be dropped too.

Step 3: upstream, the keepalive pool, and the headers Go needs

An upstream block defines a group of backend servers, and proxy_pass http://api_gateway; refers to it by name. Its other role is a connection pool:

No pool: a new connection for every request nginx Go TCP handshake → request → close, every time With a pool: connections stay and are reused nginx upstream keepalive 32 Conn 1 Conn 2 Conn 3 Go Idle longer than keepalive_timeout (60s): nginx closes it; Go’s IdleTimeout must be longer

Figure: without a pool, every request opens a new TCP connection and closes it afterwards; with a pool, the connection returns to the pool when the request ends and the next request reuses it. Connections idle for too long are closed by keepalive_timeout.

Without a pool, nginx opens a new TCP connection to Go for every request and closes it afterwards. Under heavy traffic, large numbers of connections in TIME_WAIT can exhaust local ports, and the cost of setting up a connection is paid again and again. The pool reuses connections.

upstream api_gateway {
    server 10.0.1.21:8080;     # one line per instance
    keepalive 32;              # idle connections kept per worker
    keepalive_timeout 60s;     # shorter than Go's IdleTimeout
}

There is a version difference to spell out. According to nginx's CHANGES file, since 1.29.7 upstream keepalive is on by default (32 connections per worker), the default proxy_http_version is 1.1, and Connection: close is no longer sent by default. On earlier versions (and many Linux distributions still ship older ones) you must write:

proxy_http_version 1.1;
proxy_set_header Connection "";

Otherwise nginx talks to Go over HTTP/1.0 with Connection: close, and keepalive has no effect even if you wrote it. Putting these two lines explicitly in the shared settings is correct on old and new versions alike, and the least effort. Also note that keepalive 32 limits the number of idle connections, not the total number of connections nginx opens to the backend.

Next, the headers to pass to Go. By default nginx sets Host to the host name in proxy_pass (here, api_gateway), so Go cannot see the domain, IP address or scheme the user actually used. Gather them in a shared snippet and include it in every proxying location:

# Shared settings for proxying to Go: include it in every proxy_pass location
proxy_http_version 1.1;          # default since 1.29.7; required on older versions
proxy_set_header Connection "";  # lets upstream keepalive work (required on older versions)

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;
proxy_set_header X-Request-ID      $request_id;

proxy_connect_timeout 2s;   # same data centre: failing to connect means trouble
proxy_send_timeout    15s;  # between two writes, not the whole request
proxy_read_timeout    15s;  # between two reads; longer than Go's handler deadline

proxy_next_upstream       error timeout;  # the default; a POST is not retried once sent
proxy_next_upstream_tries 2;

proxy_hide_header X-Powered-By;
HeaderValueWhat Go uses it for
Host$hostBuilding absolute URLs, decisions based on domain
X-Real-IP$remote_addrThe client IP as nginx sees it (Step 8 explains where it comes from)
X-Forwarded-For$proxy_add_x_forwarded_forThe full forwarding chain: the received value plus $remote_addr
X-Forwarded-Proto$schemeWhether the client used http or https
X-Request-ID$request_id32 hex characters generated by nginx, tying nginx and Go logs together

proxy_set_header follows the same inheritance rule as add_header in Step 6: as soon as the current level contains any proxy_set_header, none from the level above are inherited. So rather than setting headers at server level and hoping locations inherit them, every location includes the same file, and the behaviour is obvious at a glance.

X-Request-ID is overwritten with nginx's own $request_id rather than reusing a client-supplied value, because the public entry point is the first trustworthy place; api-gateway then reuses it and passes it on, as in “Building an API Gateway in Go: Routing, Authentication and Rate Limiting”. In the tests, Go received values like d226c4ca664f7d9e8553c8c2445da556.

Step 4: The slash in proxy_pass decides what the path looks like

This is one of nginx's most common traps, and the rule is one sentence from the official documentation: if proxy_pass is given a URI (even just /), the part of the path matched by the location is replaced with that URI; without a URI, the path is passed through unchanged.

Same request GET /api/orders/42: what path does Go get? nginx configuration r.URL.Path received by Go location /api/ { proxy_pass http://gw; } /api/orders/42 No URI: passed unchanged (recommended) location /api/ { proxy_pass http://gw/; } /orders/42 With /: the matched /api/ becomes / location /api { proxy_pass http://gw/; } //orders/42 Double slash; /apifoo also becomes /foo location /api/orders/ { proxy_pass http://gw/v2/orders/; } /v2/orders/42 Old and new paths written in full Trailing slashes on location and proxy_pass must come in pairs

Figure: the path Go receives for the same request, /api/orders/42, under four configurations. In the third the location lacks a trailing slash, producing a double slash, and paths such as /apifoo are accepted too.

These are the results measured in the containers, with Go echoing back the r.URL.Path it received:

ConfigurationRequestPath received by Go
location /keep/ { proxy_pass http://10.0.1.21:8080; }/keep/orders/42/keep/orders/42
location /strip/ { proxy_pass http://10.0.1.21:8080/; }/strip/orders/42/orders/42
location /noslash { proxy_pass http://10.0.1.21:8080/; }/noslash/orders/42//orders/42; Go's ServeMux answers with a 307 redirect to /orders/42
location /noslash { proxy_pass http://10.0.1.21:8080/; }/noslashfoo/foo
location /api/orders/ { proxy_pass http://10.0.1.21:8080/v2/orders/; }/api/orders/42/v2/orders/42

Rows three and four are the genuinely dangerous form: with no trailing slash on the location, /noslashfoo also matches and becomes /foo on the Go side. With real names that is location /api plus proxy_pass http://backend/;, and /apiadmin is sent to the backend's /admin. The conclusion is simple: trailing slashes on the location and on proxy_pass must come in pairs, and prefer the first form, which does not rewrite the path, so that nginx and Go see the same path and logs and routes are easy to match up.

This article's api-gateway already registers its routes under paths like /api/orders/, so the complete configuration uses proxy_pass http://api_gateway; with no slash. Rewriting paths fits when the backend is a legacy or third-party system whose paths you cannot change; then use the last row's form and write out the old and new paths in full rather than relying on a lone slash.

Without a Go gateway, nginx can also route straight to each service by path: location /api/orders/ to order, location /api/payments/ to payment. That works when there are few services and no need for central authentication; once you need to validate JWTs or rate-limit per user at the entry, go back to the approach in “Building an API Gateway in Go: Routing, Authentication and Rate Limiting” and have nginx forward only to the gateway.

Step 5: Align timeouts, request sizes, buffering and retries with Go

A request crosses three connections, each with its own timeouts, each guarding against a different problem:

Client nginx Go handler deadline Guards: slow clients client_header_timeout client_body_timeout send_timeout keepalive_timeout Guards: stuck backend proxy_connect_timeout proxy_read_timeout proxy_send_timeout upstream keepalive_timeout Last line of defence ReadHeaderTimeout ReadTimeout WriteTimeout IdleTimeout handler deadline < proxy_read_timeout < WriteTimeout upstream keepalive_timeout < Go IdleTimeout

Figure: the client-to-nginx hop guards against slow clients; the nginx-to-Go hop guards against a stuck backend; Go's own timeouts are the last line of defence, and the handler's deadline should be the shortest.

Hopnginx directive (default)Guards againstMatching Go setting
Client sends headersclient_header_timeout (60s)Holding a connection by sending headers slowly (Slowloris)ReadHeaderTimeout
Client sends bodyclient_body_timeout (60s, between two reads)Slow uploadsReadTimeout
Response to clientsend_timeout (60s, between two writes)Client not reading the responseWriteTimeout
Idle client connectionkeepalive_timeout (75s)Idle connections piling upIdleTimeout
Connecting to Goproxy_connect_timeout (60s)Backend host gone—
Waiting for Goproxy_read_timeout (60s, between two reads)Backend stuckHandler context deadline
Idle connection to Goupstream keepalive_timeout (60s)Stale pooled connectionsIdleTimeout must be longer

The order of these numbers matters more than the numbers themselves:

  • The handler deadline is the shortest, proxy_read_timeout is longer, and Go's WriteTimeout longer still. Normally Go gives up first and returns a meaningful error (say, 503 with the request ID). If Go is truly stuck, nginx returns 504 and the error log says upstream timed out ... while reading response header from upstream, which points straight at a slow backend. Make WriteTimeout the shortest instead and Go drops the connection while writing the response; nginx can only return 502, which is harder to diagnose. Designing deadline budgets is covered in “Timeouts, Retries and Circuit Breakers”. In the test, a Go handler sleeping 3 seconds behind proxy_read_timeout 2s gave the client a 504 at 2 seconds.
  • Go's IdleTimeout must be longer than nginx's upstream keepalive_timeout. Each end of an idle connection runs its own timer. If Go closes the connection just as nginx picks it up to send the next request, that request hits a connection reset. Let the side that reuses connections (nginx) close first and the race disappears. This article uses 60s for nginx and 120s for Go. The same reasoning applies between a CDN and nginx: nginx's keepalive_timeout should be longer than the CDN's idle timeout towards the origin; check your CDN's documentation for its value.
  • proxy_read_timeout and proxy_send_timeout measure the gap between two reads or writes, not the total time of the request. A streaming response that sends a little data every 10 seconds never times out under a 15-second proxy_read_timeout.

Request size. nginx's client_max_body_size defaults to 1m; anything larger gets a 413 and never reaches Go. Go should still apply a smaller, per-endpoint limit with http.MaxBytesReader, because nginx's value is shared by the whole server, and Go cannot assume it will always sit behind nginx. Tested: a 2MB body got 413 straight from nginx; 100KB passed nginx, and Go's MaxBytesReader (64KB) returned 413 request body too large; a small JSON body got 200. Each layer guards its own range; this is one of the few cases where doing it in both layers is right.

Buffering. proxy_request_buffering (on by default) makes nginx receive the entire request body before passing it to Go, and proxy_buffering (on by default) makes nginx take Go's response into its buffers and feed it to the client at the client's pace. That is the mechanism that shields Go from slow clients: Go's goroutine finishes quickly instead of trickling bytes to the client. Streaming is the exception: Server-Sent Events or long polling need each piece of data sent immediately, so set proxy_buffering off; for that location, or have Go add an X-Accel-Buffering: no header to the response (nginx recognises it and disables buffering for that response).

Retries. proxy_next_upstream defaults to error timeout: on a connection error or timeout, nginx sends the request to the next server in the upstream. The key is this sentence in the official documentation: since 1.9.13, non-idempotent requests such as POST, LOCK and PATCH are not passed to the next server once they have been sent to an upstream server, unless you add non_idempotent. So:

  • Do not add non_idempotent. POST /api/orders may already have created the order, or even charged the card, in Go, with only the response running late; if nginx sends it again, that is a duplicate order. Duplicate orders and payments are solved with idempotency keys; see “Idempotency and Distributed Locks”.
  • GETs are resent on timeout as well. If a GET actually has side effects, or is a heavy query, a resend doubles the load. Cap attempts with proxy_next_upstream_tries 2; and, where needed, set proxy_next_upstream off; on that location.
  • Retrying on the next server when the connection could not be established (the backend never received the request) is safe, even for POST. That is how nginx keeps serving while a Go instance restarts.

WebSocket and gRPC

Both need settings that differ from a normal API and are written separately from the shared snippet in Step 3 (remember the proxy_set_header inheritance rule). These are configuration fragments; their syntax was checked with nginx -t, but no WebSocket or gRPC service was actually wired up in the containers:

# Fragment: WebSocket (an http-level map plus a location)
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

location /ws/ {
    proxy_pass http://notify;
    proxy_set_header Host       $host;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_set_header Upgrade    $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_read_timeout 1h;      # default: closed after 60s without data; or have the backend send pings
}

# Fragment: gRPC (needs HTTP/2; the http2 directive exists since 1.25.1)
server {
    listen 443 ssl;
    http2 on;
    server_name grpc.shop.example.com;
    # ssl_certificate ...
    location /shop.order.v1.OrderService/ {
        grpc_pass grpc://order_grpc;       # use grpcs:// if the backend speaks TLS
        grpc_set_header X-Real-IP $remote_addr;
        grpc_read_timeout 30s;
    }
}

The WebSocket upgrade relies on the hop-by-hop headers Upgrade and Connection, which proxies do not forward by default, so they must be set explicitly. gRPC is mostly used between services, and the services from “gRPC and Protocol Buffers in Go” usually do not pass through the public nginx; you need this block only when exposing gRPC to external clients. Which API style fits where is covered in “REST, gRPC, WebSocket or Webhook: Which Fits Where”.

Step 6: Security settings at the nginx layer

TLS

ssl_protocols     TLSv1.2 TLSv1.3;
ssl_session_cache shared:SSL:10m;

ssl_protocols TLSv1.2 TLSv1.3 has been the default since nginx 1.23.4; writing it out keeps older versions the same. The cipher default (ssl_ciphers) is HIGH:!aNULL:!MD5, and TLS 1.3 suites are chosen by OpenSSL. If you need to tune them, follow the "Intermediate" profile of Mozilla's SSL Configuration Generator rather than picking your own, and recheck when you upgrade OpenSSL.

OCSP stapling used to appear on every must-have list, but it only matters when the certificate authority runs OCSP. Let's Encrypt shut down its OCSP service in August 2025 and its certificates no longer carry an OCSP URL; revocation now goes through CRLs, so enabling ssl_stapling with such certificates does nothing. With other authorities, check whether they still provide OCSP.

HSTS (Strict-Transport-Security) tells browsers "from now on, only use HTTPS for this domain". It works, but it cannot be taken back: once a browser remembers it, you cannot return to HTTP within max-age. Start with a short max-age; add includeSubDomains only when every subdomain supports HTTPS; preload writes the domain into browsers' built-in lists and takes a long time to undo, so do not add it until you are certain.

Security headers and the add_header inheritance trap

# Include again in every location that has its own add_header (see Step 6)
add_header X-Content-Type-Options "nosniff" always;
add_header Referrer-Policy "no-referrer" always;
add_header X-Frame-Options "DENY" always;
add_header Strict-Transport-Security "max-age=86400" always;  # raise gradually once verified
add_header X-Request-ID $request_id always;
HeaderWhat it blocksAPI versus web page
X-Content-Type-Options: nosniffBrowsers guessing content types and running JSON as scriptBoth
X-Frame-Options: DENY or CSP frame-ancestors 'none'Clickjacking by embedding the page in another siteRequired for pages; harmless for a pure API
Referrer-PolicyURLs (which may hold tokens or order numbers) leaking via RefererPages
Content-Security-PolicyInjected scripts running, where resources load fromPages need a per-page design; a pure JSON API can use default-src 'none'; frame-ancestors 'none'
Strict-Transport-SecurityDowngrade to HTTPBoth; mind the irreversibility above

Two details decide whether these headers are actually sent:

  • always: without it, add_header only applies to status codes 200, 201, 204, 206, 301, 302, 303, 304, 307 and 308. Error pages (404, 413, 429, 502, 504) end up without security headers. In the test, a rate-limited 429 response still carried x-content-type-options: nosniff and x-request-id because of always.
  • Inheritance: the official documentation is explicit: add_header directives are inherited from the previous level "if and only if there are no add_header directives defined on the current level".
server { … } add_header X-Content-Type-Options nosniff always; location /api/ No add_header of its own → inherits location /inherit-lost/ add_header Cache-Control "no-store" always; Has its own add_header → no inheritance Response headers X-Content-Type-Options: nosniff Response headers Cache-Control: no-store nosniff is gone One add_header at a level and nothing from the level above is inherited

Figure: the server level adds nosniff; one location writes its own add_header to set Cache-Control, and in that location every security header from the server level disappears.

In the test, the server level set X-Content-Type-Options, and the /inherit-lost/ location added only add_header Cache-Control "no-store" always;. The response contained Cache-Control alone; nosniff was gone. Three fixes:

  1. include the security header snippet again in every location that has its own add_header. Works on all versions; this article does this.
  2. add_header_inherit merge;, available since nginx 1.29.3, merges in the values from the level above. In the test, /inherit-merge/ returned both Cache-Control and X-Content-Type-Options. Use it only when your version is new enough and the whole team knows about the directive, or the next person will assume the old rule still applies.
  3. Leave security headers to a Go middleware. That is only complete when nginx never produces responses of its own (the 413, 429 and 504 that nginx returns never pass through Go).

A few more

  • server_tokens off;: the Server header and error pages say only nginx, without the version. The tested response was server: nginx. This does not remove vulnerabilities; it just stops advertising which one to use.
  • Dotfiles: location ~ /\.(?!well-known/) { return 404; } blocks .git/ and .env while keeping /.well-known/ for ACME validation. In the test, /.git/config returned 404. This only matters where nginx serves static files from a directory; API-only locations do not need it.
  • Hiding backend headers: by default nginx does not pass Date, Server, X-Pad and X-Accel-... from backend responses; remove other headers that reveal frameworks or versions with directives such as proxy_hide_header X-Powered-By;.
  • Restricting methods: limit_except GET POST { deny all; } inside a location allows only those methods (allowing GET also allows HEAD). But since Go 1.22, ServeMux routes include the method (see “net/http and Middleware in Go”) and answer 405 on a mismatch; restricting in both places means maintaining two lists, so it usually stays in Go.
  • Request smuggling: when two HTTP parsers in a row disagree about where a request ends, an attacker can "hide" a second request inside the body of the first. The defence is not a single directive but keeping both nginx and Go on versions that receive security fixes (recent nginx releases keep tightening how malformed requests are handled), and not inserting another proxy of unknown behaviour between them.
  • Only nginx can reach Go: Go listens on 127.0.0.1:8080 (same machine) or a private address, and the firewall or cloud security group allows only nginx's address to reach port 8080. Otherwise all the limits above can be bypassed, and the IP logic in Step 8 goes wrong too.
  • Encrypting to the backend (optional): when nginx and Go are on different machines and the network is not fully trusted, use proxy_pass https://... with proxy_ssl_verify on; (the default is off, meaning the backend certificate is not checked) and proxy_ssl_trusted_certificate, plus proxy_ssl_certificate and proxy_ssl_certificate_key when both sides must authenticate. The Go side of mTLS is in “Microservice Security: Authentication, Authorisation, Secrets and Supply Chain”.

Step 7: Rate limiting with a leaky bucket — rate, burst and nodelay

nginx's limit_req uses the leaky bucket algorithm. Picture a bucket for each client (key): requests pour in like water and leak out of the bottom at a fixed rate (rate) to be handled by the backend. The bucket holds burst; once it is full, further requests are rejected.

Requests from one IP burst=20: holds up to 20 rate=10r/s drains → Go Bucket full → 429 at once Without nodelay Held requests wait in a queue and are released at the rate (slower) nodelay Held requests are processed at once; free slots still return only at the rate Tested: 40 simultaneous requests → 21 × 200, 19 × 429

Figure: rate is how fast the bucket drains; burst is how many excess requests it can hold; requests beyond burst are rejected at once. Without nodelay, held requests queue and are released at the rate; with nodelay they are processed immediately but still occupy space in the bucket.

limit_req_zone  $binary_remote_addr zone=api_per_ip:10m rate=10r/s;
limit_req_status 429;

location /api/ {
    limit_req zone=api_per_ip burst=20 nodelay;
}
ParameterMeaningWhy choose it
rate=10r/s10 requests per second on average (use r/m below one per second)Estimate from normal user behaviour, not the backend's ceiling
burst=20Up to 20 requests held above the rateA page load fires several API calls at once
nodelayHeld requests are processed immediately instead of queuingAPI clients would rather fail fast than slow down mysteriously
No burstDefaults to 0: any request above the rate is rejectedAlmost never fits real traffic
limit_req_status 429The default is 503429 tells clients they are too fast, not that the server is broken
10mShared memory size; 1MB holds about 8 thousand states (64-bit platforms)10MB is about 80 thousand IPs

Tested: one client fired 40 requests at once and got 21 × 200 and 19 × 429 (one allowed by the rate plus 20 from the burst); a request from another IP immediately afterwards got 200, showing each IP has its own bucket. On another location with burst=5, 12 simultaneous requests got 6 × 200 and 6 × 429.

limit_conn covers a different dimension: the number of connections a key holds at the same time (limit_conn conn_per_ip 20;), which guards against masses of slow connections rather than request rate. When rolling out a new rule, limit_req_dry_run on; records excess requests without rejecting them, so you can watch for a while before enforcing.

What this layer's limiting fits: coarse protection keyed on IP that stops scripts, crawlers and accidental retry storms at the lowest cost. What it does not fit: per-user or per-API-key quotas and plan-based allowances, which require knowing who is calling and belong in the gateway after JWT validation (“Building an API Gateway in Go: Routing, Authentication and Rate Limiting”). And limiting by IP has a precondition: nginx must have the real client IP. That is the next step.

Step 8: Why the client IP disappears, and how to read X-Forwarded-For

A TCP connection only knows who connected directly. The client connects to the CDN, the CDN opens a new connection to nginx, and nginx opens another to Go. To nginx, $remote_addr is the CDN's IP; to Go, r.RemoteAddr is nginx's IP. The real client IP vanishes from the connection after the first hop and can only travel onwards in a header.

X-Forwarded-For is that header: each proxy appends the address that connected to it directly on the right. The problem is that clients can send their own X-Forwarded-For, and proxies only append to it; they do not clear what came before:

Client 203.0.113.50 CDN 198.51.100.20 nginx 10.0.1.10 Go realip ① Client forges 1.2.3.4 ② CDN appends 1.2.3.4 203.0.113.50 ③ nginx appends 1.2.3.4 203.0.113.50 198.51.100.20 ④ Go reads right to left 1.2.3.4 203.0.113.50 198.51.100.20 peer: nginx Ignored (forgeable) First untrusted → client CDN range: skip Trusted: read it Without realip, nginx appends the CDN address it sees (as drawn); with realip it appends the restored client IP, with the same result. Taking the leftmost value lets the client choose its own IP.

Figure: the client forges 1.2.3.4; the CDN appends the client's real IP; nginx appends the address it sees. Walking from the right and skipping trusted proxies, the first untrusted address is the real client.

So the rule for reading this header is: only the rightmost values, added by your own proxies, can be trusted; walk from right to left, skip your own proxies, and the first address that is not one of them is the client. Taking the leftmost value lets the client choose its own IP, and rate limits, audit logs and any IP-based risk checks are all bypassed.

On the nginx side: the realip module

set_real_ip_from  198.51.100.0/24;   # trust only the CDN egress ranges
real_ip_header    X-Forwarded-For;
real_ip_recursive on;

When the directly connected address is in set_real_ip_from, nginx replaces $remote_addr with a value from the header; real_ip_recursive on makes it walk from the right past every trusted address and take "the last non-trusted address", while the original peer address is kept in $realip_remote_addr. From then on, the limit_req key, $remote_addr in the logs and the X-Real-IP passed to Go are all the real client.

In the test, the CDN container's address was in 198.51.100.0/24:

ScenarioX-Forwarded-For sent to nginxX-Forwarded-For received by GoClient according to Go
Normal client via the CDN203.0.113.50203.0.113.50, 203.0.113.50203.0.113.50
Via the CDN, client forges1.2.3.4, 203.0.113.501.2.3.4, 203.0.113.50, 203.0.113.50203.0.113.50
Bypassing the CDN to nginx, forging1.2.3.41.2.3.4, 203.0.113.7203.0.113.7

The duplicate in the first row is not a bug: with realip on, $remote_addr is already the client IP, and $proxy_add_x_forwarded_for appends it once more. The third row shows why set_real_ip_from may list only the CDN's ranges: the direct address is not on the list, so nginx ignores the header and 1.2.3.4 is just an ignored string. Get the CDN's ranges from the provider (most publish a URL with the list) and update them when they change; writing 0.0.0.0/0 means trusting the whole world.

On the Go side: a realip middleware

Go should not assume it is only ever called by nginx, nor repeat nginx's logic with different rules. The realip package below applies the same "right to left, skip trusted proxies" rule, and reads the header only when the TCP peer itself is a trusted proxy:

// Package realip extracts the client IP from X-Forwarded-For sent by trusted proxies.
package realip

import (
	"context"
	"net/http"
	"net/netip"
	"strings"
)

// Resolver remembers which networks are our own proxies (nginx, CDN).
type Resolver struct {
	trusted []netip.Prefix
}

// New parses CIDR strings such as "10.0.0.0/8" and "127.0.0.1/32".
func New(cidrs ...string) (*Resolver, error) {
	r := &Resolver{}
	for _, c := range cidrs {
		p, err := netip.ParsePrefix(c)
		if err != nil {
			return nil, err
		}
		r.trusted = append(r.trusted, p.Masked())
	}
	return r, nil
}

func (r *Resolver) isTrusted(a netip.Addr) bool {
	for _, p := range r.trusted {
		if p.Contains(a) {
			return true
		}
	}
	return false
}

// ClientIP returns the client IP:
//  1. If the TCP peer is not a trusted proxy, the header may be forged: use the peer address.
//  2. Otherwise walk X-Forwarded-For from right to left, skipping trusted proxies;
//     the first untrusted address is the client.
//  3. On a malformed value, stop and return the one to its right (what the last trusted hop saw).
func (r *Resolver) ClientIP(req *http.Request) netip.Addr {
	ap, err := netip.ParseAddrPort(req.RemoteAddr)
	if err != nil {
		return netip.Addr{}
	}
	peer := ap.Addr().Unmap()
	if !r.isTrusted(peer) {
		return peer
	}
	// The header may appear several times; joined in order they form the full chain.
	var hops []string
	for _, v := range req.Header.Values("X-Forwarded-For") {
		hops = append(hops, strings.Split(v, ",")...)
	}
	client := peer
	for i := len(hops) - 1; i >= 0; i-- {
		a, err := netip.ParseAddr(strings.TrimSpace(hops[i]))
		if err != nil {
			return client
		}
		client = a.Unmap()
		if !r.isTrusted(client) {
			return client
		}
	}
	return client // the whole chain is proxies: return the leftmost
}

// Scheme uses X-Forwarded-Proto only when the peer is a trusted proxy.
func (r *Resolver) Scheme(req *http.Request) string {
	if ap, err := netip.ParseAddrPort(req.RemoteAddr); err == nil && r.isTrusted(ap.Addr().Unmap()) {
		if p := req.Header.Get("X-Forwarded-Proto"); p == "https" || p == "http" {
			return p
		}
	}
	if req.TLS != nil {
		return "https"
	}
	return "http"
}

type ctxKey struct{}

// Middleware puts the client IP into the context; handlers read it with FromContext.
func (r *Resolver) Middleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		ctx := context.WithValue(req.Context(), ctxKey{}, r.ClientIP(req))
		next.ServeHTTP(w, req.WithContext(ctx))
	})
}

// FromContext returns the client IP stored by Middleware.
func FromContext(ctx context.Context) netip.Addr {
	a, _ := ctx.Value(ctxKey{}).(netip.Addr)
	return a
}

A few design choices:

  • It uses net/netip instead of string comparisons, and Unmap normalises IPv4-mapped IPv6 addresses (::ffff:10.0.0.5).
  • A request may carry several X-Forwarded-For headers; joined in order with Header.Values, they form the full chain.
  • On a malformed value it stops and returns the address to its right (what the last trusted hop saw) instead of skipping it and carrying on leftwards; a malformed entry means that part of the chain cannot be trusted.
  • X-Forwarded-Proto is also used only when the peer is trusted. A client that sends X-Forwarded-Proto: https itself could otherwise make the service think the connection is encrypted, causing wrong redirects or Secure cookies being issued when they should not be.

The tests list the various forgeries as a table:

package realip

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestClientIP(t *testing.T) {
	// 10.0.0.0/8 is the private network nginx lives in; 198.51.100.0/24 plays the CDN egress range.
	r, err := New("10.0.0.0/8", "198.51.100.0/24")
	if err != nil {
		t.Fatal(err)
	}
	tests := []struct {
		name   string
		remote string
		xff    []string
		want   string
	}{
		{"direct, no header", "203.0.113.7:51000", nil, "203.0.113.7"},
		{"direct with own header: ignored", "203.0.113.7:51000", []string{"1.2.3.4"}, "203.0.113.7"},
		{"via nginx", "10.0.0.5:40000", []string{"203.0.113.7"}, "203.0.113.7"},
		{"via CDN and nginx", "10.0.0.5:40000", []string{"203.0.113.7, 198.51.100.20"}, "203.0.113.7"},
		{"client forges leftmost", "10.0.0.5:40000", []string{"1.2.3.4, 203.0.113.7, 198.51.100.20"}, "203.0.113.7"},
		{"forged trusted address", "10.0.0.5:40000", []string{"203.0.113.7, 10.9.9.9, 198.51.100.20"}, "203.0.113.7"},
		{"multiple headers joined in order", "10.0.0.5:40000", []string{"1.2.3.4", "203.0.113.7"}, "203.0.113.7"},
		{"stop at malformed value", "10.0.0.5:40000", []string{"203.0.113.7, garbage, 198.51.100.20"}, "198.51.100.20"},
		{"whole chain is proxies", "10.0.0.5:40000", []string{"10.0.0.9"}, "10.0.0.9"},
		{"proxy sent no header", "10.0.0.5:40000", nil, "10.0.0.5"},
		{"IPv6 client", "10.0.0.5:40000", []string{"2001:db8::1"}, "2001:db8::1"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			req := httptest.NewRequest(http.MethodGet, "/", nil)
			req.RemoteAddr = tt.remote
			for _, v := range tt.xff {
				req.Header.Add("X-Forwarded-For", v)
			}
			if got := r.ClientIP(req).String(); got != tt.want {
				t.Errorf("ClientIP = %s, want %s", got, tt.want)
			}
		})
	}
}

func TestScheme(t *testing.T) {
	r, _ := New("10.0.0.0/8")
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.Header.Set("X-Forwarded-Proto", "https")

	req.RemoteAddr = "203.0.113.7:51000"
	if got := r.Scheme(req); got != "http" {
		t.Errorf("untrusted peer: got %s, want http", got)
	}
	req.RemoteAddr = "10.0.0.5:40000"
	if got := r.Scheme(req); got != "https" {
		t.Errorf("trusted peer: got %s, want https", got)
	}
}

func TestMiddleware(t *testing.T) {
	r, _ := New("10.0.0.0/8")
	var got string
	h := r.Middleware(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		got = FromContext(req.Context()).String()
	}))
	req := httptest.NewRequest(http.MethodGet, "/", nil)
	req.RemoteAddr = "10.0.0.5:40000"
	req.Header.Set("X-Forwarded-For", "1.2.3.4, 203.0.113.7")
	h.ServeHTTP(httptest.NewRecorder(), req)
	if got != "203.0.113.7" {
		t.Errorf("got %s", got)
	}
}

go vet and go test both pass. The trusted ranges come from configuration (“Configuration and Graceful Shutdown in Go”); on the Go side you usually list only nginx's network, and add the CDN's ranges as well if nginx does not use realip.

Step 9: Server settings on the Go side

nginx stops most slow and oversized requests, but Go's http.Server still needs full settings, for two reasons: Go cannot assume nginx will always be in front (development, internal calls, a broken configuration change), and the connection between nginx and Go can go wrong too. What each timeout means was explained in “net/http and Middleware in Go”; here we only look at what matters behind nginx:

// http.Server settings for api-gateway behind nginx; the handlers are only illustrations.
package main

import (
	"context"
	"encoding/json"
	"errors"
	"log/slog"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"syscall"
	"time"

	"example.com/shop/internal/realip"
)

func main() {
	log := slog.New(slog.NewJSONHandler(os.Stdout, nil))

	// Trust only the network nginx lives in; supplied by configuration, e.g. "10.0.0.0/8".
	rip, err := realip.New(strings.Split(getenv("TRUSTED_PROXIES", "127.0.0.1/32"), ",")...)
	if err != nil {
		log.Error("bad TRUSTED_PROXIES", "err", err)
		os.Exit(1)
	}

	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		writeJSON(w, map[string]string{
			"path":       r.URL.Path,
			"client_ip":  realip.FromContext(r.Context()).String(),
			"scheme":     rip.Scheme(r),
			"request_id": r.Header.Get("X-Request-ID"),
			"xff":        r.Header.Get("X-Forwarded-For"),
		})
	})
	mux.HandleFunc("POST /api/orders", func(w http.ResponseWriter, r *http.Request) {
		r.Body = http.MaxBytesReader(w, r.Body, 64<<10) // one layer each, with nginx client_max_body_size
		var req struct {
			Note string `json:"note"`
		}
		if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
			var tooBig *http.MaxBytesError
			if errors.As(err, &tooBig) {
				http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
				return
			}
			http.Error(w, "invalid json", http.StatusBadRequest)
			return
		}
		writeJSON(w, map[string]string{"status": "created"})
	})
	mux.HandleFunc("GET /slow", func(w http.ResponseWriter, r *http.Request) {
		select {
		case <-time.After(3 * time.Second):
			writeJSON(w, map[string]string{"status": "done"})
		case <-r.Context().Done(): // nginx gives up and closes the connection; the context is cancelled
		}
	})

	srv := &http.Server{
		Addr:              getenv("ADDR", "127.0.0.1:8080"), // loopback only; outsiders must go through nginx
		Handler:           rip.Middleware(mux),
		ReadHeaderTimeout: 5 * time.Second,
		ReadTimeout:       15 * time.Second,
		WriteTimeout:      30 * time.Second,
		IdleTimeout:       120 * time.Second, // longer than the nginx upstream keepalive_timeout (60s default)
		MaxHeaderBytes:    32 << 10,
		ErrorLog:          slog.NewLogLogger(log.Handler(), slog.LevelWarn),
	}

	ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
	defer stop()

	errc := make(chan error, 1)
	go func() {
		log.Info("listening", "addr", srv.Addr)
		errc <- srv.ListenAndServe()
	}()

	select {
	case err := <-errc: // failed to start, e.g. port in use
		log.Error("server", "err", err)
		os.Exit(1)
	case <-ctx.Done():
	}
	// SIGTERM: stop accepting connections and let in-flight requests finish; nginx sends new requests to other instances.
	shutdownCtx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()
	if err := srv.Shutdown(shutdownCtx); err != nil {
		log.Error("shutdown", "err", err)
	}
}

func writeJSON(w http.ResponseWriter, v any) {
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(v)
}

func getenv(k, def string) string {
	if v := os.Getenv(k); v != "" {
		return v
	}
	return def
}
  • Addr defaults to 127.0.0.1:8080: loopback only, unreachable from other machines except through nginx. When nginx is on another machine, use a private address and restrict sources with a firewall.
  • IdleTimeout is 120 seconds, longer than nginx's upstream keepalive_timeout of 60 seconds, for the reason given in Step 5.
  • MaxHeaderBytes is 32KB: Go's default is 1MB (http.DefaultMaxHeaderBytes), too generous for a JSON API. nginx's large_client_header_buffers defaults to 4 × 8k and returns 400 for a single header field longer than 8k, so normally Go never sees bigger headers; the limit is there so as not to depend on the layer in front.
  • The illustrative /slow handler waits on r.Context().Done(): after nginx gives up because of proxy_read_timeout and closes the connection, the context on the Go side is cancelled and the handler can stop, instead of carrying on with work nobody is waiting for.

Shutting down in step with nginx. Shutdown closes the listening socket, so nginx's new connections to this instance fail; because the request has not been sent yet, proxy_next_upstream error passes it to another server in the upstream, which is safe even for POST. A sturdier order, though, is:

  1. Mark the instance in the upstream as server 10.0.1.21:8080 down; (or remove the line), run nginx -t, then nginx -s reload.
  2. Wait a little for in-flight requests and pooled connections to finish.
  3. Send SIGTERM to Go; Shutdown waits for in-flight requests to complete.

This is the same idea as Kubernetes' "fail readiness first, then wait a few seconds" in “Configuration and Graceful Shutdown in Go”: move the traffic away first, then stop the program. Note also that with a single server in an upstream, max_fails and fail_timeout are ignored and that server is never marked unavailable; for zero-downtime restarts the upstream needs at least two.

Step 10: Logs, the complete configuration and the rollout procedure

JSON access logs

log_format shop_json escape=json
  '{"time":"$time_iso8601","request_id":"$request_id",'
  '"client":"$remote_addr","peer":"$realip_remote_addr",'
  '"method":"$request_method","uri":"$uri","status":$status,'
  '"bytes":$body_bytes_sent,"request_time":$request_time,'
  '"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
  '"upstream_time":"$upstream_response_time"}';

Two real log lines from the tests:

{"time":"2026-11-21T18:19:24+00:00","request_id":"9fe1998bb0ce786bc2631bb2c8b58b6a","client":"203.0.113.50","peer":"198.51.100.20","method":"GET","uri":"/api/x","status":429,"bytes":162,"request_time":0.000,"upstream":"","upstream_status":"","upstream_time":""}
{"time":"2026-11-21T18:19:24+00:00","request_id":"9771531ed69483968fbe68fcae9b4e0a","client":"203.0.113.51","peer":"198.51.100.20","method":"GET","uri":"/api/x","status":200,"bytes":145,"request_time":0.000,"upstream":"10.0.1.21:8080","upstream_status":"200","upstream_time":"0.000"}
  • client is the client resolved by realip and peer is the CDN that actually connected; log both, so that when something goes wrong you can tell whether it was the CDN or the client.
  • The first line's upstream is empty: the 429 was returned by nginx itself and never reached Go. This field is how you tell "blocked by nginx" from "answered by Go".
  • request_time minus upstream_time is the time spent between nginx and the client (slow networks, uploads).
  • request_id matches request_id in the Go logs, so one request can be followed from nginx through every service; tracing goes further in “Observability in Go: Logs, Metrics and Tracing”.
  • Deliberately not logged: $http_authorization, $http_cookie, $request_body. Use $uri (without the query string) rather than $request_uri, because query strings often contain tokens or personal data. escape=json stops quotes and control characters sent by clients from breaking the JSON.

The complete configuration

Put together, the settings from the steps above are the file below, plus snippets/proxy-api.conf from Step 3 and snippets/security-headers.conf from Step 6. It is included inside the http block of the image's built-in nginx.conf:

# /etc/nginx/conf.d/shop.conf — included from the http block of nginx.conf

# ---- Real client IP: trust only the CDN egress ranges ----
set_real_ip_from  198.51.100.0/24;   # replace with the CDN's published ranges
real_ip_header    X-Forwarded-For;
real_ip_recursive on;

# ---- Rate limiting keyed on the real client IP ----
limit_req_zone  $binary_remote_addr zone=api_per_ip:10m rate=10r/s;
limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;
limit_req_status  429;
limit_conn_status 429;

server_tokens off;
client_max_body_size 1m;
client_header_timeout 10s;
client_body_timeout   10s;

log_format shop_json escape=json
  '{"time":"$time_iso8601","request_id":"$request_id",'
  '"client":"$remote_addr","peer":"$realip_remote_addr",'
  '"method":"$request_method","uri":"$uri","status":$status,'
  '"bytes":$body_bytes_sent,"request_time":$request_time,'
  '"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
  '"upstream_time":"$upstream_response_time"}';

upstream api_gateway {
    server 10.0.1.21:8080;     # one line per instance
    keepalive 32;              # idle connections kept per worker
    keepalive_timeout 60s;     # shorter than Go's IdleTimeout
}

# ---- Unknown Host: drop the connection, send nothing ----
server {
    listen 80  default_server;
    listen 443 ssl default_server;
    ssl_reject_handshake on;
    return 444;
}

# ---- Port 80 only redirects ----
server {
    listen 80;
    server_name shop.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl;
    http2 on;
    server_name shop.example.com;

    ssl_certificate     /etc/nginx/certs/shop.crt;
    ssl_certificate_key /etc/nginx/certs/shop.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_session_cache   shared:SSL:10m;

    access_log /var/log/nginx/shop.access.log shop_json;

    include snippets/security-headers.conf;

    # Front-end static files
    location / {
        root /srv/shop-web;
        try_files $uri /index.html;
    }

    # Never serve dotfiles such as .git and .env (keep .well-known for ACME)
    location ~ /\.(?!well-known/) {
        return 404;
    }

    location /api/ {
        limit_req  zone=api_per_ip burst=20 nodelay;
        limit_conn conn_per_ip 20;
        include snippets/proxy-api.conf;
        proxy_pass http://api_gateway;
    }
}

Rollout procedure

Configuration goes into version control like code and is reviewed before it ships. Secrets (the certificate's private key) stay out of the repository; the deployment process places them on the host, readable only by root. Every change follows the same order:

Rolling out a configuration change (real output, abridged) ① $ vi /etc/nginx/snippets/proxy-api.conf # typo: proxy_read_timeot ② $ nginx -t nginx: [emerg] unknown directive "proxy_read_timeot" in /etc/nginx/snippets/proxy-api.conf:13 nginx: configuration file /etc/nginx/nginx.conf test failed ③ $ nginx -t # after the fix nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx: configuration file /etc/nginx/nginx.conf test is successful ④ $ nginx -s reload [notice] 58#58: signal process started [notice] 1#1: worker process 30 exited with code 0 ⑤ $ curl -sk -D - -o /dev/null https://shop.example.com/api/orders/42 HTTP/2 200 x-content-type-options: nosniff x-request-id: 1ff3fef70b169f973965c076502d22df

Figure: ① edit the snippet; ② nginx -t catches the mistyped directive; ③ after the fix the check passes; ④ reload applies the new configuration; ⑤ curl confirms the behaviour. Output taken from the tests.

  • Always run nginx -t. In the test, proxy_read_timeout mistyped as proxy_read_timeot made nginx -t report unknown directive "proxy_read_timeot" in /etc/nginx/snippets/proxy-api.conf:13 and fail with exit code 1; no reload happens, and the configuration in service is unaffected.
  • Reload, do not restart. nginx -s reload (or systemctl reload nginx) makes the master process check the configuration and start new workers; old workers stop accepting new connections and exit after finishing their current requests. A restart drops every connection. In the test log, the old workers can be seen ending with exited with code 0.
  • After reloading, check the key behaviours with curl: security headers, redirects, the default server's 444, rate limits and size limits. Write these checks as a script and run it on every rollout.

Step 11: What belongs in nginx and what belongs in Go

JobnginxGo api-gatewayServices (order, payment…)
TLS termination, HTTP to HTTPSYesNoNo (mTLS between services instead)
Unknown Hostdefault_server + 444——
Request sizeclient_max_body_size (overall cap)MaxBytesReaderPer-endpoint MaxBytesReader
Slow clientsBuffering and client_*_timeouthttp.Server timeouts (safety net)http.Server timeouts
Rate limitingCoarse, keyed on IPPer user / API keyBusiness limits (e.g. payment attempts per card)
Real client IPrealip, trusting only the CDNrealip middleware, trusting only nginxUse the value passed down by the gateway
Authentication (JWT)NoYesVerify the identity passed by the gateway
Authorisation (BOLA)NoNoYes
Request IDGenerates $request_idReuses and passes onReuses
Security headersYes (including error pages)Do not duplicateDo not duplicate
CORSOne or the otherOne or the other (better: rules next to routes)No
RetriesConnection failures only; no non_idempotentAs in “Timeouts, Retries and Circuit Breakers”Idempotency keys
Access logsJSON, no tokensStructured logs with request IDSame

The principle: nginx does the jobs that do not need to know who the user is — the earlier they are stopped, the cheaper; decisions that need identity go to the Go gateway; decisions that need data stay in the service that owns the data. Each job lives in one layer, unless, as with request size, each layer genuinely protects a different range.

Common pitfalls

  • Unpaired slashes on location and proxy_pass. location /api with proxy_pass http://backend/; sends /apiadmin to the backend's /admin.
  • One add_header in a location wipes out every security header from above. proxy_set_header behaves the same. Use included snippets, or add_header_inherit merge on 1.29.3 and later.
  • Security headers without always. Error pages carry no security headers, and error pages are what attackers see most.
  • Rate limiting on $binary_remote_addr behind a CDN. All users share a handful of CDN IPs; when one person trips the limit, everyone behind that CDN node is blocked.
  • An overly wide set_real_ip_from, or taking the leftmost X-Forwarded-For value in Go. Clients get to choose their own IP.
  • Go listening on 0.0.0.0 with no firewall. Anyone can bypass nginx, connect to Go directly and forge every X-Forwarded-* header.
  • Adding proxy_next_upstream ... non_idempotent. A POST already processed by the backend, just slow to answer, is sent to another server and done again: a duplicate order.
  • On older nginx, writing keepalive without proxy_http_version 1.1 and Connection "". The connection pool does nothing.
  • Go's IdleTimeout shorter than nginx's upstream keepalive_timeout. Occasional connection resets that are hard to reproduce.
  • Leaving proxy_buffering on for SSE or streaming endpoints. nginx holds the data and the client receives it late, all at once.
  • Logging $request_uri, Authorization or bodies. Tokens and personal data get copied everywhere the logs go.
  • Applying changes with a restart, or reloading without nginx -t. The first drops connections; the second will not load the broken configuration, but the broken file stays on disk and nginx fails to start at the next reboot or restart.
  • Starting with a long HSTS and preload. When you later find a subdomain that cannot do HTTPS yet, there is no taking it back.

Key takeaways

  • A reverse proxy receives requests on behalf of servers; nginx goes in front of Go for TLS termination, buffering slow clients, static files, coarse rate limiting and a single entry point. Where an Ingress exists or Go can cope alone, skip the extra layer.
  • Use default_server with return 444 and ssl_reject_handshake on to drop unknown Hosts; port 80 only issues 301 redirects.
  • Upstream keepalive is on by default since 1.29.7; older versions need proxy_http_version 1.1 and Connection "". Set headers in one snippet and include it in every location.
  • proxy_pass with a URI replaces the part matched by the location; pair the slashes on location and proxy_pass, and prefer not rewriting the path.
  • Timeout order: handler deadline < proxy_read_timeout < Go's WriteTimeout; Go's IdleTimeout > nginx's upstream keepalive_timeout. Request size is guarded once in nginx and once in Go.
  • Never enable non_idempotent retries; disable buffering on streaming endpoints.
  • Add security headers with always and mind add_header inheritance; server_tokens off, block dotfiles, and let only nginx reach Go.
  • limit_req is a leaky bucket: rate is the average rate, burst the excess it can hold, nodelay processes held requests at once; return 429. Limiting by IP presumes you have the real IP.
  • Read X-Forwarded-For from right to left and trust only your own proxies: nginx's realip module trusts only the CDN, and Go's realip middleware trusts only nginx.
  • JSON access logs carry request_id and upstream_time but no tokens or bodies; configuration lives in version control, and every change goes through nginx -t, reload and curl checks.

References

  • How nginx processes a request (official nginx documentation): how a server is chosen by server_name and how the default server works, used in step 2.
  • Module ngx_http_upstream_module (official nginx documentation): the keepalive connection pool and its default since 1.29.7, used in step 3.
  • Module ngx_http_proxy_module (official nginx documentation): proxy_pass, proxy_http_version, timeouts, buffering and proxy_next_upstream, used in steps 3 to 5.
  • WebSocket proxying (official nginx documentation): forwarding the Upgrade and Connection headers, used in step 5.
  • Module ngx_http_headers_module (official nginx documentation): always, inheritance rules and add_header_inherit for add_header, used in step 6.
  • Module ngx_http_limit_req_module (official nginx documentation): rate, burst and nodelay for leaky-bucket rate limiting, used in step 7.
  • Module ngx_http_realip_module (official nginx documentation): set_real_ip_from, real_ip_header and real_ip_recursive, used in step 8.
  • net/http (Go standard library): the http.Server timeouts and MaxBytesReader, used in steps 5 and 9.

Next

At this point the shop has protection at every level, from nginx at the entrance, through the Go gateway and mTLS between services, down to individual database fields. These settings are full of details, and they are exactly what is easiest to break in one "quick tidy-up": an extra add_header, a missing slash, a trusted range written as 0.0.0.0/0. The next article, “Building Go Microservices with Claude Code: Rules, Permissions and Security Review”, looks at bringing an AI agent into development and using project rules, permission settings and hooks so that it keeps to the same constraints when it changes configuration and code like this.