Forward vs Reverse Proxies
"A "gateway" (a.k.a. "reverse proxy") is an intermediary that acts as an origin server for the outbound connection but translates received requests and forwards them inbound to another server or servers." — RFC 9110, HTTP Semantics, section 3.7
Summary: A proxy is a program that sits in the middle of a connection and speaks for someone. A forward proxy speaks for the clients (it decides what they may reach and hides them from the origins); a reverse proxy speaks for the servers (it decides which server answers and hides the fleet from the clients). Almost every production request today crosses at least one reverse proxy, so the details (which header carries the client address, who may be believed, which timer produces a 504) are daily work, not theory. Focus: Forward proxies (egress control, caching, filtering, HTTP CONNECT tunnels, explicit vs transparent, PAC files, SOCKS5), reverse proxies (TLS termination vs passthrough, routing, caching, compression, rate limiting, WAF, header rewriting), L4 vs L7, X-Forwarded-For, Forwarded, X-Real-IP and the trusted-proxy problem, PROXY protocol, hop-by-hop headers, buffering, timeouts and the 502 vs 504 split, upstream keepalive, HTTP/2 vs HTTP/1.1 upstream, WebSocket proxying, health checks, graceful reload, sidecars and API gateways, with Go and Laravel 13 code and tests. Learning goal: Given a request path, name every proxy on it, say which of them terminates TLS, which header each one appends and which address each one is allowed to believe, state the timeout that fires first when the application is slow, and configure NGINX, HAProxy, Envoy, Go and Laravel so that the client address, scheme and host reach the application unforged.
This chapter sits in the Networking & Protocols group of system design. It owns the proxy as a design element. The mechanics around it live in siblings: Load Balancing owns the balancing algorithms, CDN owns edge caching as a product, Service Mesh & Sidecar owns the proxy-per-pod model, API Gateway, BFF & Service Mesh owns the gateway as an architecture decision, Rate Limiting Algorithms owns the algorithms behind a limiter, Timeouts, Retries & Jitter owns the retry math, and Cryptography, TLS, PKI & Secrets owns certificate design. The bytes under all of it are in TLS in Practice, Ports, Sockets & Connections and NAT, DHCP & Port Forwarding. Persian version: /fa/system-design/proxies-forward-reverse.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why proxies exist and the trade they make | Why it exists |
| RFC 9110, SOCKS, X-Forwarded-For, PROXY protocol history | Where it comes from |
| Egress control, filtering, caching, 407 | Forward proxy |
| HTTPS through a proxy, the tunnel | HTTP CONNECT |
| Non-HTTP traffic through a proxy | SOCKS5 |
| Configured vs intercepted proxies, PAC files | Explicit, transparent and PAC |
| What a reverse proxy does for a server fleet | Reverse proxy |
| Byte relay vs HTTP-aware proxy | L4 vs L7 |
| Who holds the certificate | TLS termination, passthrough, re-encryption |
| X-Forwarded-For, Forwarded, X-Real-IP | Forwarding headers |
| Forged client IPs, Laravel TrustProxies | The trusted-proxy problem |
| Client address at L4 | PROXY protocol |
| Connection, Upgrade, Via | Hop-by-hop headers |
| Slow clients, big bodies, streaming | Buffering |
| 502 vs 504 and every timer | Timeouts |
| HTTP/2 front, HTTP/1.1 back, connection pools | Connection reuse |
| Chat, SSE, long-lived connections | WebSocket proxying |
| Ejecting dead servers, safe retries | Health checks |
| Deploying config without dropping requests | Graceful reload |
| Caching, compression, rate limiting, WAF at the proxy | What else a reverse proxy does |
| Sidecar and API gateway | Sidecar and gateway |
| NGINX, HAProxy, Envoy, Traefik, Caddy, Squid, Cloudflare, ALB | Products |
| Knobs, status codes, log lines | Mechanics |
| Code | Go, Laravel |
| Classic production failures | Solving the classic problems |
| Which proxy for which job | Choosing |
| Monolith to distributed system | In architecture |
| A lab you can run in a terminal | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Forward vs reverse. Same mechanism, opposite owner.
| Forward proxy (egress proxy) | Reverse proxy (gateway) | |
|---|---|---|
| Who configures it | The client side: browser, OS, PAC file, environment variable, or a network device | The server side: whoever owns the domain |
| How traffic reaches it | The client is told about it (explicit) or is silently steered to it (transparent) | DNS points the public name at it |
| Whom it hides | The clients from the origins | The origins from the clients |
| Typical jobs | Egress allow-list, content filtering, shared cache, audit log, anonymity | TLS termination, routing, load balancing, caching, compression, rate limiting, WAF |
| Request form | Absolute-form GET http://host/path or CONNECT host:443 | Normal origin-form GET /path with a Host header |
| Typical products | Squid, corporate secure web gateways, tinyproxy | NGINX, HAProxy, Envoy, Traefik, Caddy, Cloudflare, AWS ALB |
Layer 4 vs layer 7. The layer decides what the proxy can see and therefore what it can do.
| L4 proxy (TCP/UDP) | L7 proxy (HTTP) | |
|---|---|---|
| Sees | IP addresses, ports, bytes, sometimes the TLS SNI name | Method, path, headers, cookies, body |
| Can do | Balance connections, TLS passthrough, fail over | Route by path or host, rewrite headers, cache, limit per user, retry a request |
| Cannot do | Route by URL, add X-Forwarded-For, cache | Handle protocols it does not parse |
| Cost | Cheap, very fast, protocol-agnostic | CPU for parsing and TLS; it is a full HTTP implementation you must trust |
| Examples | HAProxy mode tcp, AWS NLB, NGINX stream | NGINX http, HAProxy mode http, Envoy HTTP connection manager, AWS ALB |
The client address problem. After one proxy, the TCP peer is the proxy. The original address survives only if the proxy writes it down and the next hop believes only proxies it knows.
| Mechanism | Layer | Written by | Believe it when |
|---|---|---|---|
| X-Forwarded-For | HTTP | Every proxy appends the peer it saw | The TCP peer is a proxy you operate; read from the right |
| Forwarded (RFC 7239) | HTTP | Proxies that support the standard form | Same rule; parse for=, proto=, host=, by= |
| X-Real-IP | HTTP | One proxy, usually the outermost you own | The proxy overwrote it, never copied the client value |
| PROXY protocol v1/v2 | TCP | The L4 proxy, once at the start of the connection | The listener accepts it only from known proxies |
| CF-Connecting-IP (Cloudflare) | HTTP | Cloudflare edge | Only when the request really came from Cloudflare ranges |
Who answers when it fails.
| Symptom | Status | Who produced it | First thing to check |
|---|---|---|---|
| Upstream refused or reset the connection | 502 Bad Gateway | The proxy | Is the app listening, was it restarting, did the port change |
| Upstream sent garbage or closed mid-response | 502 Bad Gateway | The proxy | App crash, header too large, protocol mismatch (HTTP to a TLS port) |
| Upstream did not answer in time | 504 Gateway Timeout | The proxy | The proxy read timeout versus the real work time |
| No healthy upstream left | 502 or 503 (product dependent) | The proxy | Health check, deploy in progress, ejection |
| Client sent the body too slowly | 408 Request Timeout | The proxy | Mobile clients, body timeout |
| Body bigger than allowed | 413 Content Too Large | The proxy | client_max_body_size in NGINX |
Why it exists
A direct connection from a client to a server gives both sides full information and full exposure: the server learns the client address and sees every byte of the client's behaviour; the client can reach any server it can route to. That is simple, and it breaks four things at scale.
- Control. An organisation wants to say which sites its machines may reach, and log it. A server fleet wants to say which public requests reach which service. Neither can be done well inside every application.
- Shared work. TLS, compression, caching, rate limiting, authentication of the edge and request logging are the same for every service. Doing them once in a proxy is cheaper than doing them in every codebase.
- Decoupling. Clients should not know how many servers exist, which one is being deployed, or which port the app uses. A proxy gives the public name a stable face.
- Protection. The application server is slow, stateful and full of business logic. A proxy absorbs slow clients, bad requests and floods before they occupy a worker.
The price: one more hop (about 0.1 to 1 ms inside a data centre), one more thing to fail, one more place where the truth about the client is rewritten, and one more set of timers that can disagree with yours.
| Simple direct connection | Proxy in the middle |
|---|---|
| Server sees the real peer address | Server sees the proxy; the real address travels in a header you must trust carefully |
| One TLS handshake, end to end | TLS may end at the proxy; the hop behind it may be plain or re-encrypted |
| One timeout story | A timer per hop; the smallest wins and produces a different status code |
| Nothing to deploy | A fleet, config, certificates, reloads and monitoring of its own |
| Clients know the server | Clients know the name; the proxy knows the servers |
An everyday picture. A reverse proxy is the reception desk of an office building: visitors only know the street address, reception checks who they are, sends them to the right floor, turns away trouble, and tells the person upstairs "a visitor from the courier company is on the way". A forward proxy is the company mail room for outgoing post: staff hand it letters, it checks they may be sent, stamps them with the company return address, and keeps a log. The visitor's name written on a note by reception is useful only if the person upstairs knows the note really came from reception and not from a visitor who wrote it himself. That note is X-Forwarded-For.
Three common misunderstandings, up front
- "A proxy is a security product." A proxy is a place where security controls can live; by itself it also adds a new component that can leak, mis-route and spoof.
- "X-Forwarded-For tells you the client IP." It tells you what the last untrusted party wrote, followed by what each proxy appended. Only the entries added by your own proxies are facts.
- "A 504 means the application is slow, a 502 means it is down." A 504 means the proxy's timer fired; the application may still be working (and will finish the work after the client has left). A 502 means the proxy could not get a valid response, including after a crash mid-response.
Where it comes from
The word "proxy" in HTTP is defined, in the current specification, as "a message-forwarding agent that is chosen by the client, usually via local configuration rules, to receive requests for some type(s) of absolute URI" (RFC 9110, section 3.7). The same section defines the gateway ("a.k.a. reverse proxy") and the tunnel ("a blind relay between two connections without changing the messages"). Those three words are the whole vocabulary of this chapter.
| Date | Milestone | Source |
|---|---|---|
| 1996 | SOCKS Protocol Version 5 (RFC 1928) generalises a firewall-traversal framework to any application protocol; it adds authentication negotiation and UDP | RFC 1928 |
| Long established | Caching forward proxies such as Squid ("a high-performance proxy caching server for web clients") are an established product category | Squid FAQ (undated) |
| Before 2014 | X-Forwarded-For, X-Forwarded-By and X-Forwarded-Proto exist as "non-standard header fields" used by common load balancers | RFC 7239, section 1 |
| 2014 | RFC 7239 standardises the Forwarded header field with for, by, host and proto parameters | RFC 7239 |
| 2012 to 2020 | HAProxy's PROXY protocol (v1 text, v2 binary) lets "dumb" TCP proxies pass the original connection parameters | HAProxy proxy-protocol spec |
| 2022 | RFC 9110 consolidates HTTP semantics: proxy, gateway, tunnel, CONNECT, Via, hop-by-hop handling in the Connection field | RFC 9110 |
| Today | Envoy ("an L7 proxy and communication bus") runs beside every service as an out-of-process proxy | Envoy docs |
The PROXY protocol row spans the revision dates in the specification's own changelog (the first entries are from 2012, the latest from 2020). The Squid row carries no date because the page read does not give one.
The concept catalogue
Forward proxy and egress control Must-know
In plain words: A forward proxy is a server you route your outgoing traffic through. Instead of each laptop or server connecting straight to the internet, they ask the proxy to connect for them, and the proxy can say yes, no, or "from cache".
Common misunderstanding: "A forward proxy is for hiding your IP." Anonymity is one use. In companies the main uses are the opposite: control (an egress allow-list), accountability (every request logged with who sent it), and saving bandwidth with a shared cache. A server that may call only three external APIs and nothing else is a forward proxy use case, and it is the one that stops data exfiltration and SSRF from becoming incidents.
Definition: An intermediary chosen by the client that receives requests for absolute URIs (GET http://example.org/a HTTP/1.1) or tunnel requests (CONNECT example.org:443) and forwards them to the origin, applying policy on the way. The policy points are: who may use it (authentication, 407), where they may go (allow or deny by domain, category or IP), what happens to the response (cache, scan, rewrite) and what is recorded.
1 app -> proxy CONNECT api.payments.example:443 HTTP/1.1 Proxy-Authorization: Basic ...
2 proxy policy: service "billing" may reach *.payments.example:443 -> allow
3 proxy -> origin TCP connect to api.payments.example:443
4 proxy -> app HTTP/1.1 200 Connection Established
5 app <-> origin TLS handshake and HTTPS, relayed blindly by the proxy
6 proxy log: billing -> api.payments.example:443, 12.4 KB up, 88 KB down, 340 msReal scenario: A bank allows application servers to reach only a payment provider and a time server; everything else is dropped at the firewall and permitted solely through Squid with an allow-list. A research lab caches OS package downloads in Squid so a hundred machines pull the same file once. A SaaS runs customer-supplied webhook URLs through a hardened egress proxy that refuses private address ranges, which is the standard SSRF defence for outbound fetches. A school filters categories of sites.
| Product | Role as forward proxy | Notes |
|---|---|---|
| Squid | Caching and filtering forward proxy; ACLs in squid.conf (`http_access allow | deny`) |
| NGINX | Can forward plain HTTP with resolver and proxy_pass $http_host$request_uri, but has no native CONNECT support | Use a CONNECT module or a purpose-built forward proxy for HTTPS |
| HAProxy | Mostly reverse; can be a plain forward relay with ACLs | Not designed as a filtering forward proxy |
| Envoy | Dynamic forward proxy filter for in-mesh egress | Egress gateway pattern in service meshes |
| Cloud NAT / firewall appliances | L3/L4 egress, no HTTP awareness | Combine with a proxy when you need domain-level policy |
Fix / how to use it: the code in Go shows a forward proxy with a destination allow-list and proxy authentication. On the Laravel side, application egress is pointed at the proxy with Guzzle's proxy option passed through Http::withOptions (see Laravel). Never try to enforce an egress allow-list only in the application: it must be enforced where a compromised application cannot switch it off, the network and the proxy.
-- Egress audit table fed by the proxy log (PostgreSQL)
CREATE TABLE egress_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
logged_at timestamptz NOT NULL DEFAULT now(),
source_ip inet NOT NULL,
principal text NOT NULL, -- authenticated proxy user or service name
method text NOT NULL, -- GET, CONNECT ...
destination text NOT NULL, -- host:port
decision text NOT NULL CHECK (decision IN ('allow','deny')),
bytes_up bigint NOT NULL DEFAULT 0,
bytes_down bigint NOT NULL DEFAULT 0
);
CREATE INDEX egress_log_dest_idx ON egress_log (destination, logged_at DESC);
-- Which services talk to destinations nobody approved?
SELECT principal, destination, count(*) AS denied
FROM egress_log
WHERE decision = 'deny' AND logged_at > now() - interval '1 day'
GROUP BY principal, destination
ORDER BY denied DESC
LIMIT 20;HTTP CONNECT and tunnels Must-know
In plain words: HTTPS is encrypted from your machine to the website, so a proxy cannot read it. CONNECT is the request "please open a TCP pipe to that host and port and then just pass bytes". After the proxy says 200, it stops being an HTTP participant and becomes a pipe.
Common misunderstanding: "A forward proxy can see my HTTPS URLs." With CONNECT it sees only the destination host and port (and, if it also looks at the handshake, the SNI name), the amount of data and the timing. It cannot see the path, headers or body unless it performs TLS interception: it presents its own certificate, your device trusts the company root CA, and the proxy opens a second TLS session to the origin. That is a deliberate man-in-the-middle and must be disclosed and managed as such.
Definition: RFC 9110, section 9.3.6: "The CONNECT method requests that the recipient establish a tunnel to the destination origin server identified by the request target and, if successful, thereafter restrict its behavior to blind forwarding of data, in both directions, until the tunnel is closed." The request target is in authority-form (host:port), not a path.
1 client -> proxy CONNECT shop.example:443 HTTP/1.1
Host: shop.example:443
Proxy-Authorization: Basic c3ZjOnMzY3JldA==
2 proxy -> origin TCP SYN to shop.example:443
3 proxy -> client HTTP/1.1 200 Connection Established
4 client -> origin TLS ClientHello (SNI: shop.example), relayed
5 origin -> client ServerHello, certificate, Finished, relayed
6 client <-> origin encrypted application data; proxy copies bytes both ways
7 either side closes -> proxy closes the other half (half-close is propagated)Real scenario: HTTPS_PROXY=http://proxy.corp.example:3128 curl https://api.example.org issues the exchange above. A CI runner behind a corporate proxy needs HTTPS_PROXY and NO_PROXY set, otherwise npm install hangs. A proxy that answers 403 to CONNECT for a destination on a block list is the normal "blocked by policy" experience. Some proxies allow CONNECT only to port 443; allowing it to arbitrary ports turns the proxy into a generic TCP relay, which attackers use to reach internal services (the proxy-as-pivot problem).
| Product | CONNECT behaviour |
|---|---|
| Squid | Supported; restricted by acl SSL_ports port 443 and http_access deny CONNECT !SSL_ports in the default config |
| NGINX | http module does not implement CONNECT; use the stream module or a different proxy |
| HAProxy | Can accept CONNECT in mode http with ACLs on the authority |
| Envoy | CONNECT supported with upgrade_configs: CONNECT and tunnelling (used for HTTP/2 and HTTP/3 proxying) |
Go net/http client | Honors HTTPS_PROXY through http.ProxyFromEnvironment and issues CONNECT automatically |
Fix / how to use it: the Go forward proxy in Go implements the connect method: check policy on the authority, dial with a timeout, hijack the client connection, reply 200 Connection Established, copy both directions, and propagate half-close with CloseWrite. The test TestConnectTunnelsBytes proves bytes go both ways; TestConnectDeniedByPolicy proves a 403.
SOCKS5 Good to know
In plain words: SOCKS5 is a proxy protocol below HTTP. The client says "connect me to this address and port" in a small binary message, and the proxy relays any protocol: SSH, SMTP, a database, a game.
Common misunderstanding: "SOCKS is just a faster HTTP proxy." SOCKS does not understand HTTP at all, so it cannot cache, filter by URL or add headers. Its strength is generality, which is also the reason security teams treat it with suspicion.
Definition: RFC 1928 defines three steps. The client sends a version identifier and a list of authentication methods (X'00' no authentication, X'02' username/password, X'FF' none acceptable from the server); the server picks one; the client then sends a request with CMD (CONNECT, BIND or UDP ASSOCIATE), an address type (IPv4, domain name or IPv6), the destination address and port; the server replies with a status and the bound address.
1 client -> proxy 05 02 00 02 version 5, two methods: none, user/pass
2 proxy -> client 05 02 chosen method: username/password
3 client -> proxy 01 04 'svc' 06 's3cret' RFC 1929 sub-negotiation
4 proxy -> client 01 00 authentication ok
5 client -> proxy 05 01 00 03 0B 'example.org' 01 BB CONNECT, domain name, port 443
6 proxy -> client 05 00 00 01 <bound addr/port> succeeded
7 client <-> origin raw bytes relayed (any protocol)Real scenario: ssh -o ProxyCommand through a SOCKS proxy; curl --socks5-hostname proxy:1080 (hostname resolved by the proxy, which avoids DNS leaks); ssh -D 1080 bastion creating a local SOCKS5 proxy over an SSH tunnel; Tor exposes a SOCKS5 port. In Kubernetes, SOCKS is rare; HTTP CONNECT or mesh egress is used instead.
| Question | HTTP proxy with CONNECT | SOCKS5 |
|---|---|---|
| Understands HTTP | Yes for plain requests, no after CONNECT | No |
| Non-HTTP protocols | Only via CONNECT on allowed ports | Native |
| UDP | No | UDP ASSOCIATE |
| DNS resolution at the proxy | Yes, authority carries the host name | Yes with the domain-name address type (socks5h in curl) |
| Authentication | Proxy-Authorization (407) | Method negotiation (RFC 1929 username/password) |
| Policy granularity | Domain, URL (plain), method | Destination address and port only |
Fix / how to use it: prefer HTTP CONNECT where the client supports it, because Squid-style ACLs are richer. Use SOCKS5 when the protocol is not HTTP. In Go, golang.org/x/net/proxy provides a SOCKS5 dialer; in Laravel, SOCKS is not covered by the Laravel or Guzzle pages read for this chapter, so check the cURL handler documentation before relying on it.
Explicit proxy, transparent proxy and PAC files Important
In plain words: An explicit proxy is one the client knows about and is configured to use. A transparent (intercepting) proxy is one the network quietly steers traffic into, so the client never knows.
Common misunderstanding: "Transparent means invisible to security tools." Transparent only means the client needs no configuration. HTTPS interception needs a trusted CA on the client, and anything the proxy cannot decrypt (certificate pinning, mTLS) breaks. Explicit proxies fail loudly (the client reports proxy errors); transparent ones fail strangely (connection resets, certificate warnings).
Definition: Explicit proxy: the client sends absolute-form requests or CONNECT to the proxy's address. Transparent proxy: the router or firewall redirects TCP port 80 and 443 to the proxy (iptables REDIRECT/TPROXY, a WCCP router, or a cloud firewall); the proxy recovers the destination from the original destination socket option or from the Host header and SNI. A PAC (proxy auto-config) file is a JavaScript function FindProxyForURL(url, host) that the browser downloads and runs for each URL; it returns DIRECT, PROXY host:port, SOCKS5 host:port or a semicolon separated fallback list.
1 browser -> wpad/PAC server GET http://wpad.corp.example/proxy.pac
2 browser runs FindProxyForURL("https://api.corp.example/x", "api.corp.example")
3 browser result "DIRECT": connects straight to the internal API
4 browser runs FindProxyForURL("https://news.example.org/", "news.example.org")
5 browser result "PROXY proxy1.example:3128; PROXY proxy2.example:3128"
6 browser -> proxy1 CONNECT news.example.org:443 (proxy2 only if proxy1 is unreachable)Real scenario: A laptop fleet gets its PAC URL from MDM; internal names go DIRECT and everything else goes to the proxy pool. A Kubernetes cluster uses a transparent egress gateway (an Envoy or Squid pod) with iptables redirection from the node so that workloads need no HTTP_PROXY variables. A developer sees ERR_TUNNEL_CONNECTION_FAILED in Chrome: the PAC file returned a proxy that rejected CONNECT.
| Aspect | Explicit | Transparent |
|---|---|---|
| Client config | Needed (proxy settings, PAC, env vars) | None |
| Failure visibility | Clear proxy error pages and 407/403 | Resets, timeouts, certificate warnings |
| HTTPS | CONNECT; host and port visible, content opaque unless intercepted | Needs interception with a trusted CA, or only SNI-based decisions |
| Authentication | 407 Proxy-Authentication Required | Hard: usually by source IP or device certificate |
| Typical place | User laptops, CI runners | Branch networks, egress gateways, guest Wi-Fi |
Fix / how to use it: see the sample PAC below. Keep PAC logic short (it runs for every URL in the browser), return DIRECT for internal names and ranges first, never return DIRECT as a fallback if policy requires the proxy.
// Proxy auto-config (PAC): a JavaScript function the browser calls per URL.
function FindProxyForURL(url, host) {
if (isPlainHostName(host) || dnsDomainIs(host, ".internal.example")) {
return "DIRECT"; // never proxy internal names
}
if (isInNet(host, "10.0.0.0", "255.0.0.0")) {
return "DIRECT";
}
// Primary proxy, then a standby, then give up (do not fall back to DIRECT: that would bypass policy).
return "PROXY proxy1.example:3128; PROXY proxy2.example:3128";
}Reverse proxy Must-know
In plain words: A reverse proxy is the front door of your servers. Clients connect to it thinking it is the website; it passes each request to a real server behind it and passes the answer back.
Common misunderstanding: "A reverse proxy is just a load balancer." Load balancing is one of at least a dozen jobs: TLS termination, routing by host or path, caching, compression, rate limiting, request size limits, authentication offload, header normalisation, WAF rules, access logs, redirects, canary traffic splitting and graceful draining during deploys. A load balancer that understands HTTP is a reverse proxy; a reverse proxy with one backend is still useful.
Definition: An HTTP gateway: it accepts the client connection as if it were the origin, then opens its own connection to an upstream server (an origin or an application server), forwards a possibly rewritten request, and relays the response. The two connections are independent: different TLS sessions, different HTTP versions, different keepalive state, different timeouts. The set of backends is the upstream (NGINX term; HAProxy calls it a backend, Envoy a cluster, Traefik a service, Caddy an upstream).
1 client -> proxy TLS handshake, HTTP/2 GET /orders/42 Host: shop.example
2 proxy terminate TLS, parse request, check rate limit and WAF rules
3 proxy route: Host shop.example, path /orders -> pool "orders" (2 healthy of 3)
4 proxy -> orders-2 GET /orders/42 HTTP/1.1 X-Forwarded-For: 198.51.100.7 X-Forwarded-Proto: https
5 orders-2 -> proxy 200 OK, 12 KB
6 proxy add Via, strip internal headers, compress if allowed, write access log
7 proxy -> client HTTP/2 200 OKReal scenario: NGINX in front of PHP-FPM or Laravel Octane; HAProxy balancing a database pool in mode tcp; Envoy as the ingress of a Kubernetes cluster; Cloudflare in front of the whole site (a reverse proxy run by a third party); an AWS Application Load Balancer routing /api/* to one target group and / to another.
| Job | NGINX | HAProxy | Envoy | Traefik | Caddy |
|---|---|---|---|---|---|
| Basic proxying | proxy_pass | backend + server | cluster + route | router + service | reverse_proxy |
| Active health checks | Plus only (health_check) | check on server | health_checks on cluster | healthCheck on service | health_uri |
| Passive ejection | max_fails, fail_timeout | observe, on-error | outlier detection | not native | fail_duration, max_fails |
| Dynamic config | reload; Plus API | runtime API, reload | xDS APIs | providers (Docker, K8s) | API, reload |
| Typical role | Edge, app tier | Edge, L4 and L7 balancer | Mesh sidecar and gateway | Container ingress | Simple edge with automatic HTTPS |
Fix / how to use it: the working reference config is below (NGINX). It shows upstream keepalive, HTTP/1.1 to the upstream, forwarding headers, tight timeouts, retries, a WebSocket location and buffering choices; each of these is explained in its own block.
# NGINX reverse proxy in front of an application tier (L7).
# Reload without dropping connections: nginx -t && nginx -s reload
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream app {
zone app 64k; # shared memory so all workers see the same state
server 10.0.1.11:8080 max_fails=2 fail_timeout=10s;
server 10.0.1.12:8080 max_fails=2 fail_timeout=10s;
keepalive 32; # idle upstream connections kept per worker
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on; # HTTP/2 to the client ...
server_name app.example.com;
ssl_certificate /etc/nginx/tls/app.example.com.pem;
ssl_certificate_key /etc/nginx/tls/app.example.com.key;
# Believe the PROXY protocol or X-Forwarded-For only from our own L4 load balancer.
set_real_ip_from 10.0.0.0/8;
real_ip_header X-Forwarded-For;
real_ip_recursive on;
client_max_body_size 10m;
location / {
proxy_pass http://app;
proxy_http_version 1.1; # ... HTTP/1.1 upstream, needed for keepalive upstream
proxy_set_header Connection ""; # clear the hop-by-hop header so the connection stays open
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_connect_timeout 3s; # default 60s is far too long for a user-facing path
proxy_send_timeout 30s;
proxy_read_timeout 30s; # gap between two reads, not the whole response
proxy_next_upstream error timeout http_502 http_503;
proxy_next_upstream_tries 2; # idempotent requests only (default behaviour)
proxy_request_buffering on; # whole request body is read before the upstream sees it
proxy_buffering on; # slow clients do not tie up the app tier
}
location /ws/ {
proxy_pass http://app;
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 1h; # an idle WebSocket is silent; give it room
proxy_buffering off;
}
}Layer 4 and layer 7 proxies Must-know
In plain words: A layer 4 proxy moves bytes between two TCP connections without reading them. A layer 7 proxy reads the HTTP messages, so it can make decisions about each request.
Common misunderstanding: "L7 is always better because it knows more." L7 pays for knowledge: it must parse every message, hold buffers, and agree with the client on every HTTP detail, so it has a larger attack surface and more CPU cost. L4 is the right choice for non-HTTP protocols (databases, MQTT, SMTP), for TLS passthrough, for extreme throughput, and as the first tier that spreads connections across several L7 proxies.
Definition: L4 (transport) proxy: decisions based on the 5-tuple and, optionally, the TLS SNI name; one client connection maps to one upstream connection. L7 (application) proxy: decisions based on parsed protocol messages; one client connection can be multiplexed over many upstream connections (and the reverse).
1 client -> L4 proxy SYN
2 L4 proxy pick backend by round robin or least connections (no HTTP parsed)
3 L4 proxy -> backend SYN; then PROXY protocol header: PROXY TCP4 198.51.100.7 203.0.113.10 52341 443
4 client <-> backend TLS and HTTP flow through untouched
5 L7 proxy -> backend (alternative) parsed request, pooled connection, X-Forwarded-For addedReal scenario: AWS Network Load Balancer in front of an NGINX fleet (L4 tier spreading connections, L7 tier doing HTTP); HAProxy mode tcp in front of PostgreSQL replicas; NGINX stream for MySQL or syslog; AWS ALB routing by path; Envoy as an L3/L4 proxy with HTTP filters on top ("At its core, Envoy is an L3/L4 network proxy" with an HTTP filter on top, per its docs).
| Capability | L4 proxy | L7 proxy |
|---|---|---|
| Route by host or path | No (SNI only) | Yes |
| Preserve end-to-end TLS | Yes (passthrough) | No unless re-encrypted |
| Add or rewrite headers | No | Yes |
| Per-request retry and metrics | No (per connection) | Yes |
| Websocket and gRPC awareness | Opaque bytes | Understands Upgrade and HTTP/2 streams |
| Typical throughput cost | Lowest | Higher CPU per request |
Fix / how to use it: use an L4 tier when you need passthrough or non-HTTP protocols, and let it hand the client address to the L7 tier with the PROXY protocol. Put per-request logic in the L7 tier.
TLS termination, passthrough and re-encryption Must-know
In plain words: Someone must hold the private key and do the encryption maths. Termination means the proxy does it and talks plain HTTP behind it. Passthrough means the proxy does not touch TLS and the backend does it. Re-encryption means the proxy decrypts, inspects, then opens a new TLS connection to the backend.
Common misunderstanding: "If the proxy terminates TLS my traffic is unencrypted." Only the segment behind the proxy is plain, and only if you configure it so. In a trusted private network that may be acceptable; in a shared network, cloud multi-tenant VPC or zero-trust model you re-encrypt (and often use mTLS between proxy and upstream, see mTLS service security).
Definition: Termination (offload): the proxy completes the handshake with the client using the public certificate; upstream is HTTP or HTTPS (re-encryption) with its own trust. Passthrough: the L4 proxy relays the encrypted stream, choosing the backend with the SNI value in the ClientHello when needed. The certificate then lives on the backend.
| Model | Who has the certificate | Proxy can see the request | Cost and risk |
|---|---|---|---|
| Termination, plain upstream | Proxy | Yes | Cheapest; the hop behind the proxy is cleartext |
| Termination + re-encryption | Proxy (public) and backend (private CA) | Yes | Two handshakes; certificate management twice |
| Termination + mTLS upstream | Proxy and backend, both verify | Yes | Strong internal identity; more certificates |
| Passthrough | Backend | No (SNI and bytes only) | No L7 features at the proxy; client address needs PROXY protocol |
1 client -> proxy ClientHello (SNI shop.example, ALPN h2, http/1.1)
2 proxy holds shop.example certificate -> terminate: ServerHello with its certificate
3 client <-> proxy HTTP/2 over TLS 1.3
4 proxy -> app HTTP/1.1 over plain TCP, X-Forwarded-Proto: https
5 app builds absolute URLs; must trust X-Forwarded-Proto or it will emit http:// linksReal scenario: Cloudflare terminates TLS at its edge and connects to the origin in "Flexible" (plain) or "Full" modes; an ALB with an ACM certificate terminates TLS and speaks HTTP to targets; an NLB with TCP listeners does passthrough; a bank requires re-encryption inside the data centre. The classic bug: the app generates http:// links or redirect loops behind a terminating proxy because it believes the connection was plain; the fix is a trusted X-Forwarded-Proto (see Laravel).
Fix / how to use it: terminate at an L7 proxy for routing and WAF; pass through when the backend must own the key (regulated keys, client certificates validated by the app); re-encrypt in multi-tenant networks. Certificate lifecycle and PKI: Cryptography, TLS, PKI & Secrets. Handshake bytes: TLS in Practice.
Forwarding headers: X-Forwarded-For, Forwarded, X-Real-IP Must-know
In plain words: When a proxy forwards a request, the server sees the proxy as the sender. So the proxy adds a note: "the connection really came from this address, using this scheme, for this host".
Common misunderstanding: "X-Forwarded-For is a standard that carries one IP." It is a de facto convention, a comma-separated list; RFC 7239 calls these "non-standard header fields". Each proxy appends the address of the peer that connected to it. A client may also send its own X-Forwarded-For, which the first proxy happily keeps unless told otherwise.
Definition: X-Forwarded-For: client, proxy1, proxy2 (the last proxy's own address is not in the list; it is the TCP peer of the application). X-Forwarded-Proto carries the scheme the client used, X-Forwarded-Host the original Host, X-Forwarded-Port the original port. X-Real-IP is a single value set by one proxy (NGINX: proxy_set_header X-Real-IP $remote_addr). The standard Forwarded field (RFC 7239) combines them in one header: Forwarded: for=192.0.2.60;proto=http;by=203.0.113.43, with IPv6 and unknown identifiers quoted: for="[2001:db8:cafe::17]:4711".
1 attacker -> CDN GET / X-Forwarded-For: 203.0.113.99
2 CDN -> balancer X-Forwarded-For: 203.0.113.99, 198.51.100.7 (CDN appends the peer it saw)
3 balancer -> nginx X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4 (balancer appends the CDN address)
4 nginx -> app X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4, 10.0.0.9
5 app TCP peer is 10.0.0.12; the first entry is a lie, the real client is 198.51.100.7Real scenario: A login rate limiter keyed by the first X-Forwarded-For value is bypassed with a new random header per request. An audit log shows every user coming from the load balancer's private address because the app reads REMOTE_ADDR. An allow-list for an admin panel is bypassed by sending X-Forwarded-For: 10.0.0.1 through a proxy that appends rather than replaces. AWS ALB has an attribute routing.http.xff_header_processing.mode with append (the default), preserve and remove; Cloudflare sends CF-Connecting-IP with the client address; Envoy decides the trusted client address with use_remote_address and xff_num_trusted_hops.
| Header | Standard | Format | Who writes it | Notes |
|---|---|---|---|---|
| X-Forwarded-For | De facto | Comma-separated addresses | Each proxy appends | Read right to left through trusted hops |
| X-Forwarded-Proto | De facto | http or https | The terminating proxy | Needed for correct redirects and absolute URLs |
| X-Forwarded-Host | De facto | Original Host | Proxy that rewrote Host | Only trusted from known proxies; Host header attacks |
| X-Forwarded-Port | De facto | Port number | Proxy | Absolute URLs with non-default ports |
| Forwarded | RFC 7239 | for=, by=, host=, proto= | Proxies that implement it | Adoption is partial; many stacks still use X-Forwarded-* |
| X-Real-IP | Convention (NGINX) | Single address | One chosen proxy | Must be overwritten, not passed through |
| CF-Connecting-IP | Cloudflare | Single address | Cloudflare edge | Trust only if the request came from Cloudflare |
| Via | RFC 9110 | 1.1 pseudonym | Every proxy | Diagnostics and loop detection, not identity |
Fix / how to use it: one rule: the outermost proxy you own must discard (or overwrite) any forwarding header it receives from an untrusted peer, and every inner hop trusts only the peers in a list. The Go package clientip implements the right-to-left walk and rproxy overwrites X-Real-IP and rebuilds X-Forwarded-For from a trusted-peer decision.
// Package before is the naive way to find the client address behind a proxy.
// It is bad design on purpose: it trusts a header that any client can send.
package before
import (
"net/http"
"strings"
)
// ClientIP returns the first entry of X-Forwarded-For when present.
// The first entry is whatever the original caller wrote, so an attacker
// controls it: "X-Forwarded-For: 203.0.113.99" makes any rate limiter,
// allow-list or audit log believe the request came from 203.0.113.99.
func ClientIP(r *http.Request) string {
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
return strings.TrimSpace(strings.Split(xff, ",")[0])
}
return r.RemoteAddr
}// Package clientip finds the real client address behind a chain of proxies.
//
// Rule: only believe a forwarding header when the TCP peer that delivered the
// request is a proxy you operate. Then walk X-Forwarded-For from the right
// (the entry your own proxy appended) toward the left and stop at the first
// address that is not one of your proxies.
package clientip
import (
"net"
"net/netip"
"strings"
)
// Parse turns a comma separated list of prefixes or addresses into prefixes.
func Parse(cidrs ...string) ([]netip.Prefix, error) {
out := make([]netip.Prefix, 0, len(cidrs))
for _, c := range cidrs {
if p, err := netip.ParsePrefix(c); err == nil {
out = append(out, p)
continue
}
a, err := netip.ParseAddr(c)
if err != nil {
return nil, err
}
out = append(out, netip.PrefixFrom(a, a.BitLen()))
}
return out, nil
}
// Trusted reports whether addr is inside one of the prefixes.
func Trusted(addr netip.Addr, trusted []netip.Prefix) bool {
addr = addr.Unmap()
for _, p := range trusted {
if p.Contains(addr) {
return true
}
}
return false
}
// PeerAddr extracts the address part of an http.Request.RemoteAddr.
func PeerAddr(remoteAddr string) (netip.Addr, bool) {
host, _, err := net.SplitHostPort(remoteAddr)
if err != nil {
host = remoteAddr
}
a, err := netip.ParseAddr(host)
if err != nil {
return netip.Addr{}, false
}
return a.Unmap(), true
}
// FromRequest returns the client address. xff holds every X-Forwarded-For
// header value of the request (a request may carry the header more than once).
func FromRequest(remoteAddr string, xff []string, trusted []netip.Prefix) (netip.Addr, bool) {
peer, ok := PeerAddr(remoteAddr)
if !ok {
return netip.Addr{}, false
}
if !Trusted(peer, trusted) {
return peer, true // direct client, or an untrusted hop: ignore every header
}
var chain []string
for _, v := range xff {
for _, part := range strings.Split(v, ",") {
if p := strings.TrimSpace(part); p != "" {
chain = append(chain, p)
}
}
}
client := peer
for i := len(chain) - 1; i >= 0; i-- {
a, err := netip.ParseAddr(chain[i])
if err != nil {
return client, true // garbage from a trusted hop: stop at the last good address
}
client = a.Unmap()
if !Trusted(client, trusted) {
return client, true
}
}
return client, true // every hop was ours: the leftmost entry is the best answer
}The trusted-proxy problem and Laravel TrustProxies Must-know
In plain words: The application may believe "X-Forwarded-For" only when the connection came from a proxy it knows. If the connection came from anywhere else, the header is just text from a stranger.
Common misunderstanding: "Trust all proxies with * and the problem is solved." Trusting * means any caller can spoof the headers whenever the app is reachable by a path that bypasses your proxy (a public IP, another port, a misconfigured security group, a debugging tunnel). It is acceptable only when the network guarantees that the app can be reached solely through the proxy, which is what a cloud load balancer in a private subnet gives you. Laravel's documentation suggests * for cloud balancers whose addresses you do not know; combine it with network rules.
Definition: The trusted-proxy rule has three parts. (1) A list of trusted peers (addresses or CIDR ranges). (2) Headers are believed only if the TCP peer is in the list. (3) The client address is the first address, walking the X-Forwarded-For list from the right, that is not itself a trusted proxy. Laravel implements this with the Illuminate\Http\Middleware\TrustProxies middleware: $middleware->trustProxies(at: [...], headers: ...) in bootstrap/app.php; the headers argument is a bit mask built from Request::HEADER_X_FORWARDED_FOR, HEADER_X_FORWARDED_HOST, HEADER_X_FORWARDED_PORT, HEADER_X_FORWARDED_PROTO, HEADER_X_FORWARDED_AWS_ELB and HEADER_FORWARDED. After it runs, $request->ip(), $request->isSecure(), $request->getHost() and url() use the forwarded values.
1 request from 203.0.113.50 (not trusted) with X-Forwarded-For: 10.1.2.3, X-Forwarded-Proto: https
2 TrustProxies: peer 203.0.113.50 is not in at: [10.0.0.0/8] -> headers ignored
3 $request->ip() = 203.0.113.50 $request->isSecure() = false
4 request from 10.0.0.5 (trusted) with X-Forwarded-For: 198.51.100.7, X-Forwarded-Proto: https
5 TrustProxies: peer is trusted -> read X-Forwarded-For
6 $request->ip() = 198.51.100.7 $request->isSecure() = true url('/login') = https://app.example.com/loginReal scenario: Behind an AWS ALB the app sees every request from the ALB's private address until HEADER_X_FORWARDED_AWS_ELB is trusted; after a deploy to Kubernetes the pod network CIDR changes and at no longer matches, so redirects go to http://; a staging environment trusts * and a pentest sets X-Forwarded-For: 127.0.0.1 to reach an "internal only" route.
| Stack | Trust setting | Default |
|---|---|---|
| Laravel 13 | $middleware->trustProxies(at: ..., headers: ...) | No proxies trusted |
| NGINX | set_real_ip_from + real_ip_header X-Forwarded-For + real_ip_recursive on | No addresses trusted |
| Envoy | use_remote_address and xff_num_trusted_hops on the HTTP connection manager | use_remote_address false |
| Express (Node) | app.set('trust proxy', ...) | Off |
Go net/http | No built-in; use a package like clientip below | n/a |
| AWS ALB | routing.http.xff_header_processing.mode | append |
Fix / how to use it: the snippets show the Laravel bootstrap, a controller that reports what the framework believes and a feature test that proves an untrusted peer cannot forge the address.
<?php
// bootstrap/app.php (Laravel 13): trust only the proxies you operate.
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Peers allowed to tell us about the real client. Everything else is a client.
$middleware->trustProxies(
at: explode(',', (string) env('TRUSTED_PROXIES', '10.0.0.0/8,172.16.0.0/12')),
// Believe only the headers your edge really sets. Not Forwarded if it never sends it.
headers: Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO,
);
// Reject requests whose Host header is not one of ours (host header attacks).
$middleware->trustHosts(at: ['^app\.example\.com$']);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})
->create();PROXY protocol Important
In plain words: At layer 4 there are no headers, so the proxy sends one extra line at the very start of the connection that says who the real client is.
Common misunderstanding: "Turn on the PROXY protocol on the backend and it will use it when present." The receiver must be told to expect it and must not guess. The specification says: "The receiver MUST NOT start processing the connection before it receives a complete and valid PROXY protocol header", and it explains why guessing is a security hole: it "would open a major security breach by allowing untrusted parties to spoof their connection addresses". If the listener expects the header and the proxy does not send it (or the reverse), every connection fails.
Definition: HAProxy's PROXY protocol prepends a header to the first bytes of a TCP connection. Version 1 is a human-readable line (PROXY TCP4 192.0.2.1 203.0.113.10 56324 443\r\n, at most 107 characters). Version 2 is binary with the 12-byte signature 0D 0A 0D 0A 00 0D 0A 51 55 49 54 0A, an address block, and optional TLV fields (for example the SSL information or an AWS VPC endpoint id). A proxy that already understands the transported protocol (an L7 proxy reusing connections) must not use it on multiplexed connections.
1 client 198.51.100.7:52341 -> L4 proxy 203.0.113.10:443 TCP connect
2 L4 proxy -> backend PROXY TCP4 198.51.100.7 203.0.113.10 52341 443\r\n
3 L4 proxy -> backend (then the client's bytes, e.g. TLS ClientHello)
4 backend parses the PROXY line first; its client address is now 198.51.100.7
5 backend a connection without the line from a trusted proxy -> rejectReal scenario: HAProxy send-proxy-v2 to NGINX listen 443 ssl proxy_protocol (with set_real_ip_from and real_ip_header proxy_protocol); an AWS NLB with proxy protocol v2 enabled on the target group; the same setup in front of PostgreSQL or SMTP, where no HTTP header exists at all. Mistake: enabling accept-proxy on a public port, which lets anyone claim any source address.
| Product | Send | Receive |
|---|---|---|
| HAProxy | send-proxy, send-proxy-v2 on server | accept-proxy on bind |
| NGINX | proxy_protocol on in stream server | listen ... proxy_protocol plus set_real_ip_from |
| Envoy | Proxy protocol upstream transport socket | Proxy protocol listener filter |
| AWS NLB | Target group attribute proxy_protocol_v2.enabled | n/a |
| Traefik | proxyProtocol on a TCP service | proxyProtocol.trustedIPs on an entry point |
Fix / how to use it: see the HAProxy config below: one TCP tier that sends the header, one HTTP tier that accepts it only on a private port.
# HAProxy: L4 in front (TCP, PROXY protocol, TLS passthrough) and L7 behind (HTTP).
global
log stdout format raw local0
defaults
timeout connect 3s
timeout client 30s
timeout server 30s
# L4 tier: do not look inside TLS; tell the next hop who the client was.
frontend tls_in
mode tcp
bind :443
default_backend edge_nginx
backend edge_nginx
mode tcp
server nginx1 10.0.0.21:443 send-proxy-v2 check # PROXY protocol v2 header on every new connection
# L7 tier: HTTP-aware routing, headers and health checks.
frontend http_in
mode http
bind :8080 accept-proxy # only accept the PROXY header on this trusted port
option forwardfor # adds X-Forwarded-For with the client address
http-request set-header X-Forwarded-Proto https
use_backend api if { path_beg /api/ }
default_backend web
backend web
mode http
balance roundrobin
option httpchk GET /healthz
server web1 10.0.1.11:8080 check inter 2s fall 3 rise 2
server web2 10.0.1.12:8080 check inter 2s fall 3 rise 2
backend api
mode http
balance leastconn
option httpchk GET /healthz
server api1 10.0.2.11:8080 checkHop-by-hop headers and Via Important
In plain words: Some headers talk only to the next connection, not to the final destination. A proxy must remove them and set its own.
Common misunderstanding: "A proxy copies all headers." A correct proxy drops the hop-by-hop ones. RFC 9110 section 7.6.1 says the Connection field lists connection options that apply only to the immediate recipient; headers named there are removed before forwarding. Forgetting this leaks a client's Connection: keep-alive into an upstream conversation that has its own rules, or breaks Upgrade.
Definition: The standard hop-by-hop set: Connection, Keep-Alive, Proxy-Authenticate, Proxy-Authorization, TE, Trailer, Transfer-Encoding, Upgrade (and the legacy Proxy-Connection), plus every header named in the Connection value. Via is not removed; it is appended by each intermediary: Via: 1.1 edge-1, 1.1 nginx (HTTP version and a pseudonym or host), for diagnostics and loop detection.
1 client -> proxy GET / Connection: keep-alive, X-Secret X-Secret: 1 Keep-Alive: timeout=5
2 proxy remove Connection, Keep-Alive and X-Secret (it was named in Connection)
3 proxy add Via: 1.1 edge-1
4 proxy -> origin GET / Via: 1.1 edge-1 (origin never sees X-Secret)
5 origin -> proxy 200 OK Connection: close
6 proxy -> client 200 OK Via: 1.1 edge-1 (the origin's Connection: close is not copied)Real scenario: WebSocket upgrade fails behind NGINX because Upgrade and Connection are hop-by-hop and must be set explicitly with proxy_set_header; a Go proxy built by hand with http.Client copies Connection: close and drops upstream keepalive; httputil.ReverseProxy removes hop-by-hop headers before calling Rewrite and ModifyResponse, and re-adds Connection: Upgrade for 101 responses.
| Header | Hop-by-hop | What a proxy does |
|---|---|---|
| Connection | Yes | Remove; set its own for the upstream |
| Keep-Alive | Yes | Remove |
| Proxy-Authorization | Yes | Consume at the proxy; never forward to the origin |
| Transfer-Encoding | Yes | Re-chunk per hop |
| Upgrade | Yes | Pass explicitly for WebSocket only |
| Via | No | Append 1.1 name |
| X-Forwarded-For | No | Append (trusted) or overwrite (untrusted) |
| Authorization | No | End-to-end; forward |
Fix / how to use it: the Go forward proxy implements RemoveHopByHop and the reverse proxy leans on the standard library; both are tested (TestRemoveHopByHop, TestUntrustedClientCannotForgeForwardingHeaders).
Buffering: request and response Important
In plain words: A proxy can either hold a message until it is complete before passing it on (buffering), or pass bytes along as they arrive (streaming). Buffering protects slow application servers from slow clients.
Common misunderstanding: "Buffering only costs memory." Buffering also changes behaviour: server-sent events and live streams stall because the proxy waits for more bytes; a large upload is fully received before the app sees the first byte, so the app cannot reject early; a disk spill can fill a volume. Turning buffering off protects streaming and costs the protection against slow clients.
Definition: NGINX proxy_request_buffering on (default): "the entire request body is read from the client before sending the request to a proxied server"; when off it is sent as it arrives and the request cannot be passed to the next server once sending started. proxy_buffering on (default): the response is read as fast as possible into memory buffers (proxy_buffer_size, proxy_buffers) and, if it does not fit, spilled to a temporary file (proxy_max_temp_file_size). With it off, "the response is passed to a client synchronously, immediately as it is received".
1 client (3G, 50 KB/s) -> proxy upload 5 MB takes ~100 s
2 proxy request buffering ON: reads all 5 MB first
3 proxy -> app sends 5 MB over a fast LAN in ~50 ms; app worker busy only for ~50 ms
4 (buffering OFF) app worker is held ~100 s waiting on the slow client
5 app -> proxy -> client response 2 MB: proxy buffers and releases the app in ~20 msReal scenario: A PHP-FPM pool exhausted by slow uploads is fixed by request buffering at NGINX; an SSE endpoint stuck until 4 KB accumulates is fixed with proxy_buffering off or the X-Accel-Buffering: no response header; a 2 GB video upload fills /var/lib/nginx/body and the disk; a Go server streaming a log needs FlushInterval set on httputil.ReverseProxy (the sample uses -1, flush immediately).
| Product | Request body | Response |
|---|---|---|
| NGINX | proxy_request_buffering (default on) | proxy_buffering (default on), X-Accel-Buffering per response |
| HAProxy | Buffers per request up to tune.bufsize; option http-buffer-request waits for the body | Streams after headers |
| Envoy | Buffer filter; per-route stream idle timeouts | Streams by default, flow control by watermarks |
Go httputil.ReverseProxy | Streams the incoming body | FlushInterval controls flushing |
| Caddy | request_buffers, response_buffers options on reverse_proxy | flush_interval |
Fix / how to use it: buffer for ordinary APIs and uploads (protects the app tier), unbuffer for streaming and long-polling locations, and cap body sizes at the proxy (client_max_body_size in NGINX) with the same number the application validates.
Timeouts and the 502 vs 504 split Must-know
In plain words: Every proxy has several stopwatches: one for connecting to the server, one for sending the request, one for waiting for the answer. When one runs out the proxy gives up and tells the client who failed.
Common misunderstanding: "proxy_read_timeout is the maximum time a request may take." It is not. The NGINX documentation says: "The timeout is set only between two successive read operations, not for the transmission of the whole response." A server that sends one byte every 59 seconds never trips a 60-second read timeout. And the proxy's default (60 s) is usually longer than a user is willing to wait, and often longer than the client's own timeout, so the client gives up first and the proxy logs a 499.
Definition: RFC 9110: 502 Bad Gateway means the proxy "received an invalid response from an inbound server it accessed while attempting to fulfill the request"; 504 Gateway Timeout means it "did not receive a timely response from an upstream server it needed to access". In practice: connect refused or reset = 502, bytes that are not HTTP = 502, connect timeout or read timeout = 504 (NGINX logs these as upstream timed out; the status a client sees is 504). NGINX defaults: proxy_connect_timeout 60s (it "cannot usually exceed 75 seconds"), proxy_send_timeout 60s, proxy_read_timeout 60s.
1 t=0.0 client -> proxy POST /export
2 t=0.0 proxy -> app connect ok, request sent
3 t=30.0 proxy proxy_read_timeout 30s: no response bytes -> closes upstream connection
4 t=30.0 proxy -> client 504 Gateway Timeout
5 t=47.2 app finishes the export and writes to a closed socket (work done, nobody to tell)
6 t=47.2 app its database transaction committed; the user retries and the export runs twiceReal scenario: A report endpoint takes 70 s and returns 504 from the ALB's 60 s idle timeout (the AWS default); the fix is to make the endpoint asynchronous (202 Accepted and a status URL, see Service Communication), not to raise timeouts forever. A deploy restarts the app and clients see a burst of 502 for a few hundred milliseconds. An application returns a response header of 16 KB, larger than proxy_buffer_size, and NGINX answers 502 and logs "upstream sent too big header". A Go service behind Envoy sets a 15 s server write timeout and the proxy's 30 s route timeout never matters.
| Timer | NGINX | HAProxy | Envoy | ALB (AWS) |
|---|---|---|---|---|
| Connect to upstream | proxy_connect_timeout (60s) | timeout connect | cluster connect_timeout | fixed by the service |
| Wait for or between response bytes | proxy_read_timeout (60s) | timeout server | route timeout, idle_timeout | idle timeout attribute (60 s default) |
| Send request to upstream | proxy_send_timeout (60s) | timeout server | route timeout | n/a |
| Slow client | client_body_timeout, send_timeout | timeout client | stream idle, request timeouts | idle timeout |
| Tunnel / WebSocket idle | proxy_read_timeout | timeout tunnel | upgrade idle timeout | idle timeout |
Fix / how to use it: order the budgets (client timeout greater than proxy timeout greater than app work) as discussed in Timeouts, Retries & Jitter, propagate a deadline, make long work asynchronous, and treat 504 as "outcome unknown" for non-idempotent requests (the app may still complete the work, so write idempotent endpoints, see API Idempotency). The Go proxy maps timeouts to 504 and everything else to 502 and tests both.
Connection reuse, HTTP/2 front and HTTP/1.1 back Important
In plain words: Opening a TCP (and TLS) connection per request is slow. A proxy keeps a pool of open connections to each upstream and reuses them; the client side and the upstream side are separate conversations and can use different HTTP versions.
Common misunderstanding: "If the client speaks HTTP/2 my app sees HTTP/2." Most proxies speak HTTP/2 or HTTP/3 to the client and HTTP/1.1 to the upstream, and that is usually fine: multiplexing exists to save connections across the long, lossy internet path, not across a LAN. One more trap: NGINX's old default of HTTP/1.0 to the upstream had no keepalive; the documentation of proxy_http_version says that before 1.29.7 version 1.0 was the default and since then 1.1 is, and recommends 1.1 or 2 "for use with keepalive connections". Always set it explicitly if you must support older builds.
Definition: Upstream keepalive keeps idle connections open. NGINX: keepalive N; inside upstream, with proxy_http_version 1.1 and proxy_set_header Connection "" on older builds; since 1.29.7 "by default the cache for connections is activated". HAProxy: option http-reuse safe|aggressive|always. Envoy: connection pools per cluster per worker thread, HTTP/1.1 or HTTP/2 chosen by the cluster typed_extension_protocol_options. Go: http.Transport with MaxIdleConnsPerHost (the default is 2, far too low for a proxy) and IdleConnTimeout.
1 without keepalive: every request pays TCP handshake (1 RTT) + TLS handshake (1 RTT TLS 1.3) + request
2 upstream RTT 0.5 ms in the same zone -> 1.5 ms of handshakes on a 5 ms request = 30 % overhead
3 with keepalive 32: the pool holds idle connections, the 99th request reuses one -> 0 handshakes
4 danger: the upstream closes idle connections after 5 s, the proxy sends on a connection closed a moment ago -> reset, 502
5 rule: upstream idle timeout must be longer than the proxy's idle connection lifetimeReal scenario: Sporadic 502 under low traffic with "upstream prematurely closed connection" because Node.js keepAliveTimeout (5 s) is shorter than NGINX's idle connection lifetime; ALB 502 with a target that closes idle connections faster than the ALB's 60 s idle timeout; a Go proxy opening a new connection per request because MaxIdleConnsPerHost is 2 and traffic is 500 rps.
| Hop | Typical protocol | Why |
|---|---|---|
| Client to proxy | HTTP/2 or HTTP/3 over TLS | Fewer connections, header compression, multiplexing on a lossy path |
| Proxy to upstream (same VPC) | HTTP/1.1 keepalive | Simple, pooled, no multiplexing gain on a LAN |
| Proxy to gRPC service | HTTP/2 (h2c or TLS) | gRPC requires HTTP/2 end to end |
| L4 proxy to anything | Opaque | Passes bytes, no version negotiation |
Fix / how to use it: the reference NGINX config sets keepalive 32, HTTP/1.1 and Connection ""; the Go proxy sets MaxIdleConnsPerHost: 64, IdleConnTimeout: 90s and ForceAttemptHTTP2: false for HTTP/1.1 upstream. More on HTTP versions: HTTP Evolution.
WebSocket proxying and Upgrade Important
In plain words: A WebSocket starts as a normal HTTP request that asks to switch protocols; after the server agrees, the connection becomes a raw two-way pipe. A proxy must carry the request, pass the agreement and then stay out of the way.
Common misunderstanding: "WebSockets just work through any proxy." Because Upgrade and Connection are hop-by-hop, a proxy removes them unless you tell it to pass them. And the proxy still has timeouts: an idle WebSocket looks like a dead upstream connection and is closed at 60 seconds by default in NGINX.
Definition: The client sends Connection: Upgrade and Upgrade: websocket; the server answers 101 Switching Protocols. NGINX: set both headers explicitly (proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade";) and, on older builds, proxy_http_version 1.1; the nginx documentation notes that "since the 'Upgrade' is a hop-by-hop header, it is not passed from a client to proxied server" and says that "with forward proxying, clients may use the CONNECT method to circumvent this issue". Go's ReverseProxy handles 101 responses itself. Envoy needs upgrade_configs: [upgrade_type: websocket].
1 client -> proxy GET /ws Connection: Upgrade Upgrade: websocket Sec-WebSocket-Key: ...
2 proxy sees Upgrade: re-adds Connection: Upgrade and Upgrade: websocket for the upstream
3 proxy -> app GET /ws Connection: upgrade Upgrade: websocket
4 app -> proxy 101 Switching Protocols
5 proxy -> client 101 Switching Protocols from here the proxy copies bytes both ways
6 idle for 60 s proxy_read_timeout fires -> connection closed; fix with 1h or application pings every 25 sReal scenario: Laravel Reverb or a chat server drops every connection at exactly 60 seconds; the cure is a longer proxy_read_timeout on the /ws/ location and heartbeat pings. A sticky session is not needed for WebSocket itself (the connection is one TCP stream) but is needed for stateful protocols layered on top (Socket.IO long-polling fallback). Draining on deploy: the old workers keep the open sockets until clients reconnect. More about the transport choice: Real-time: Polling, SSE & WebSockets.
| Product | WebSocket setup |
|---|---|
| NGINX | proxy_set_header Upgrade/Connection, long proxy_read_timeout |
| HAProxy | Automatic with mode http; timeout tunnel for idle length |
| Envoy | upgrade_configs with websocket |
| Traefik, Caddy | Automatic |
| AWS ALB | Native WebSocket support; the idle timeout applies |
| Cloudflare | Supported on all plans; idle behaviour per plan |
Fix / how to use it: the /ws/ block in the NGINX config sets the headers and a one hour read timeout; TestUpgradeIsTunnelled proves a 101 upgrade and echo through the Go proxy.
Health checks, retries and ejection Must-know
In plain words: The proxy must know which servers are alive. It either probes them (active health check) or learns from failures of real traffic (passive health check) and takes dead ones out of rotation.
Common misunderstanding: "Retrying a failed request on another server is always safe." A request that failed after it was sent may already have been executed. NGINX documents this: "normally, requests with a non-idempotent method (POST, LOCK, PATCH) are not passed to the next server if a request has been sent to an upstream server"; the option non_idempotent explicitly allows it. Safe retries need an idempotent method (or an idempotency key) and a failure that happened before any byte was delivered.
Definition: Active check: the proxy requests GET /healthz at an interval; fall failures mark the server down, rise successes mark it up (HAProxy check inter 2s fall 3 rise 2). Passive check: failures of real requests count (max_fails=2 fail_timeout=10s in NGINX: after two failures within the window the server is skipped for the window). Outlier detection in Envoy ejects hosts returning consecutive 5xx. A health endpoint must report readiness (can serve) separately from liveness (should be restarted), as in Kubernetes.
1 proxy -> app-2 GET /healthz 200 up
2 deploy starts: app-2 stops accepting connections
3 proxy -> app-2 GET /healthz refused fail 1 of 3
4 client -> proxy GET /cart -> picks app-2 -> connect refused (retryable, GET, no bytes sent)
5 proxy -> app-1 GET /cart 200 client never sees the failure
6 proxy fail 3 of 3 -> app-2 ejected for 10 s; probes continue; rise 2 -> back in rotationReal scenario: A deploy where the load balancer keeps sending traffic to a pod that is shutting down (needs a preStop delay and connection draining); a health endpoint that checks the database and takes the whole fleet out when the database blips, a self-inflicted outage; "no live upstreams while connecting to upstream" when all are ejected (the Go pool deliberately keeps one in rotation rather than failing everything). Details of load-balancing algorithms and sticky sessions are in Load Balancing.
| Product | Active | Passive | Retry control |
|---|---|---|---|
| NGINX (open source) | No; NGINX Plus health_check | max_fails, fail_timeout | proxy_next_upstream, proxy_next_upstream_tries |
| HAProxy | check, option httpchk | observe layer7, on-error | retries, option redispatch |
| Envoy | health_checks | outlier_detection | route retry_policy with retry_on |
| Traefik | healthCheck | circuit-breaker middleware | retry middleware |
| Caddy | health_uri | fail_duration, max_fails | lb_try_duration, lb_try_interval |
| AWS ALB | Target group health check | n/a | Retries to another target only on connection failure |
Fix / how to use it: the Go rproxy retries only idempotent, body-less requests and only on dial errors, ejects the failing upstream, and runs an active CheckLoop against /healthz.
Graceful reload Important
In plain words: A proxy must pick up new config, new certificates or a new binary without cutting requests in flight.
Common misunderstanding: "Restart is the same as reload." A restart closes every connection. A reload starts new workers with the new config and lets old workers finish what they are doing.
Definition: NGINX: send HUP to the master (nginx -s reload): "the master process first checks the syntax validity, then tries to apply new configuration... If this fails, it rolls back changes and continues to work with old configuration" and, on success, "starts new worker processes, and sends messages to old worker processes requesting them to shut down gracefully". Always run nginx -t first. HAProxy: reload starts a new process that takes over the listening sockets and the old one finishes its connections (-sf or master-worker reload). Envoy: hot restart or, more commonly, dynamic xDS updates with no process restart. Caddy: caddy reload or the admin API. Go: http.Server.Shutdown(ctx) stops accepting and drains.
1 operator nginx -t test configuration -> ok
2 operator nginx -s reload HUP to master
3 master start new workers with the new config; listening sockets are shared
4 old workers stop accepting; finish in-flight requests and open WebSocket connections
5 new workers accept new connections immediately
6 old workers exit when idle (worker_shutdown_timeout bounds the wait)Real scenario: A certificate renewed by cron followed by a reload; a pipeline that deploys a config change at peak traffic with zero 502s; a reload that never finishes because a WebSocket keeps an old worker alive for days (set worker_shutdown_timeout); an invalid config reload that is rejected and the old config keeps serving (the reason to prefer reload).
| Product | Reload | In-flight requests |
|---|---|---|
| NGINX | nginx -s reload (HUP) | Old workers drain |
| HAProxy | systemctl reload haproxy (master-worker) | Old process drains; hard-stop-after bounds it |
| Envoy | xDS updates; hot restart optional | Drain period per listener |
| Traefik | Watches providers, no reload needed | Graceful by design |
| Caddy | caddy reload, admin API | Graceful |
Fix / how to use it: validate, reload, watch error rate; for deploys of the application tier use connection draining plus readiness checks so the proxy stops sending new requests before the pod stops.
What else a reverse proxy does: caching, compression, rate limiting, WAF, redirects Important
In plain words: Because every request passes through it, the proxy is the cheapest place to do work that every service needs.
Common misunderstanding: "Put everything at the proxy." Business rules, per-user authorization and anything needing the database belong in the application. The proxy handles cross-cutting concerns that need only the HTTP message, and each feature added is also a feature to configure, test and upgrade.
Definition and examples: Response caching (NGINX proxy_cache, Varnish, Cloudflare; see Caching and CDN); compression (gzip or Brotli, saving bytes on text); rate limiting (NGINX limit_req, Envoy local and global rate limit filters; algorithms in Rate Limiting Algorithms); WAF (ModSecurity with the OWASP Core Rule Set, Cloudflare WAF, AWS WAF on an ALB) for generic attack signatures (see OWASP Top 10); request ID injection (X-Request-Id) and trace propagation; redirects from HTTP to HTTPS and canonical hosts; basic authentication or JWT validation at the edge; header normalisation (strip Server, add HSTS); request body limits; static file serving; canary traffic splitting by weight or header.
1 request GET /product/42?utm=ad Cookie: session=...
2 proxy WAF rules: no SQLi signature -> pass
3 proxy rate limit key (real client IP): 38 req in 1 s > 20 r/s burst 40 -> allow, delay
4 proxy cache lookup: key "GET shop.example/product/42" -> HIT (age 12 s, TTL 60 s), no upstream call
5 proxy compress response with gzip (text/html), add HSTS and X-Request-Id
6 proxy -> client 200 OK X-Cache: HITReal scenario: A flash sale protected by a per-client rate limit at the proxy (which depends on the correct client IP, see forwarding headers; a limiter keyed by the balancer's address throttles everyone at once); an API behind AWS WAF blocking known bad bots; a marketing page cached for 60 seconds absorbing a traffic spike so the app tier sees 1 request per minute per page.
| Duty | NGINX | HAProxy | Envoy | Cloudflare / ALB |
|---|---|---|---|---|
| Cache | proxy_cache | Small cache (cache section) | HTTP cache filter | Cloudflare CDN; ALB none |
| Rate limit | limit_req, limit_conn | stick-table | Rate limit filters | Cloudflare rules; ALB with AWS WAF |
| WAF | ModSecurity module | ModSecurity SPOE | WAF via filters (Coraza, ext_authz) | Cloudflare WAF, AWS WAF |
| Auth at edge | auth_request, JWT in Plus | Lua, http-request auth | ext_authz, jwt_authn | ALB OIDC authenticate action |
| Compression | gzip, Brotli module | compression algo | Compressor filter | Cloudflare automatic |
Fix / how to use it: configure these at the proxy only where the data is available there; and remember the proxy must know the real client IP for any of the per-client features.
Sidecars and API gateways Important
In plain words: The same proxy idea shows up at two other scales: a small proxy next to each service (sidecar), and a smart proxy at the edge for all APIs (gateway).
Common misunderstanding: "A service mesh replaces the API gateway" or the reverse. The gateway handles north-south traffic from outside (authentication of external clients, plans, quotas, request shaping); the mesh handles east-west traffic between services (mTLS, retries, telemetry). They overlap in technology (both can run Envoy) and differ in purpose.
Definition: Sidecar: a proxy process deployed in the same pod or host as one application instance, intercepting its inbound and outbound traffic (Envoy "designed to run alongside every application server"; "each application sends and receives messages to and from localhost and is unaware of the network topology"). API gateway: a reverse proxy at the edge with API-specific features (routing by version, authentication, quotas, transformation, developer portal). Mechanics of sidecars: Service Mesh & Sidecar; the decision between gateway, BFF and mesh: API Gateway, BFF & Service Mesh.
1 external client -> edge gateway TLS, JWT check, rate limit, route /orders -> orders service
2 gateway -> orders pod request (mTLS to the pod's sidecar)
3 orders sidecar decrypt, enforce policy, record metrics, pass to localhost:8080
4 orders app -> sidecar call to http://payments (resolved by the mesh)
5 orders sidecar -> payments sidecar mTLS, retry policy, timeout, load balancing
6 payments sidecar -> payments app plain localhostReal scenario: Kong, Apigee, AWS API Gateway, Traefik or Envoy Gateway at the edge; Istio or Linkerd sidecars inside; a company whose gateway rejects expired JWTs so services never see them. A forward proxy appears here too: the mesh's egress gateway is a controlled forward proxy for traffic leaving the cluster.
| Dimension | Edge reverse proxy | API gateway | Sidecar proxy |
|---|---|---|---|
| Traffic | Internet to site | Internet to APIs | Service to service |
| Count | A few | One logical, several instances | One per workload instance |
| Knows about | Hosts and paths | Clients, plans, API versions | Services and identities |
| Trust boundary | Outer | Outer | Inner (mTLS) |
| Config source | Static files, Ingress | Gateway config, control plane | Mesh control plane |
Fix / how to use it: choose by the traffic it handles; see the siblings above. A proxy chain of edge proxy, gateway and sidecar means four to five hops; the forwarding-header rules from this chapter apply at every hop.
Products: what each one is for Must-know
In plain words: The same ideas are available in many programs; they differ in config style, where they are strong and how they are run.
Common misunderstanding: "They are interchangeable." They share concepts but not defaults. NGINX closes the upstream with Connection: close unless told otherwise on old builds; HAProxy health checks are on only with check; Envoy trusts no X-Forwarded-For unless use_remote_address is set correctly; Caddy provisions HTTPS automatically. Read the defaults of the one you run.
Definition (one line each): NGINX: web server and reverse proxy, event-driven workers, config files, reload. HAProxy: "a free, very fast and reliable reverse-proxy offering high availability, load balancing, and proxying for TCP and HTTP-based applications". Envoy: "an L7 proxy and communication bus designed for large modern service oriented architectures". Traefik: "an open-source Application Proxy" with dynamic config from providers such as Docker and Kubernetes. Caddy: reverse proxy and web server with automatic HTTPS. Squid: caching forward proxy. Cloudflare: global reverse proxy and CDN run as a service. AWS ALB: managed L7 balancer; AWS NLB: managed L4 balancer with connection tracking.
1 need pick
2 caching forward proxy / egress filter Squid (or a cloud secure web gateway)
3 fast edge reverse proxy, static files, PHP upstream NGINX
4 L4 + L7 balancer with strong health checks and ACLs HAProxy
5 service mesh data plane, dynamic config, gRPC Envoy (via Istio, Contour, Envoy Gateway)
6 containers, auto-discovery, small team Traefik or Caddy
7 managed on AWS, no servers to run ALB for HTTP, NLB for TCP/TLS passthrough
8 DDoS absorption, global edge, WAF as a service Cloudflare or another CDNReal scenario: A small team runs Caddy for three sites with automatic certificates; a platform team runs NGINX Ingress or Envoy Gateway in Kubernetes; a bank puts HAProxy in front of NGINX for TCP passthrough and PROXY protocol; a startup uses Cloudflare plus an ALB and trusts CF-Connecting-IP only from Cloudflare's published ranges.
| Product | Type | Config model | Strong at | Watch out for |
|---|---|---|---|---|
| NGINX | L7 and stream L4 | Files, reload | Edge, static, PHP-FPM, caching | Open source health checks are passive; CONNECT unsupported |
| HAProxy | L4 and L7 | Files, runtime API | Balancing, ACLs, stick tables, PROXY protocol | Smaller feature set for web serving |
| Envoy | L3/L4 and L7 | xDS APIs, YAML | Mesh, observability, gRPC, hot config | Learning curve; YAML volume |
| Traefik | L7 and TCP | Providers, labels | Container ingress, Let's Encrypt | Fewer low-level knobs |
| Caddy | L7 | Caddyfile, JSON, API | Automatic HTTPS, simple config | Smaller ecosystem of rules |
| Squid | Forward, cache | squid.conf ACLs | Egress control, caching, filtering | Complex ACL syntax; not a modern reverse proxy |
| Cloudflare | Global reverse proxy | Dashboard, API | DDoS, CDN, WAF | Trust ranges, TLS modes, header handling |
| AWS ALB / NLB | L7 / L4 managed | Console, IaC | No servers, integrates with ECS/EKS | Idle timeout 60 s default, limited rewriting |
Fix / how to use it: the Envoy snippet below is a minimal L7 reverse proxy; note use_remote_address: true, WebSocket upgrade, cluster health checks and a connect timeout.
# Envoy as an L7 reverse proxy: one listener, one route, one cluster with health checks.
static_resources:
listeners:
- name: ingress
address: { socket_address: { address: 0.0.0.0, port_value: 8080 } }
filter_chains:
- filters:
- name: envoy.filters.network.http_connection_manager
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager
stat_prefix: ingress
use_remote_address: true # trust the TCP peer, not the client's X-Forwarded-For
xff_num_trusted_hops: 0
upgrade_configs:
- upgrade_type: websocket
route_config:
virtual_hosts:
- name: app
domains: ["app.example.com"]
routes:
- match: { prefix: "/" }
route: { cluster: app, timeout: 30s }
http_filters:
- name: envoy.filters.http.router
typed_config:
"@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router
clusters:
- name: app
type: STRICT_DNS
connect_timeout: 3s
health_checks:
- timeout: 1s
interval: 5s
unhealthy_threshold: 3
healthy_threshold: 2
http_health_check: { path: /healthz }
load_assignment:
cluster_name: app
endpoints:
- lb_endpoints:
- endpoint: { address: { socket_address: { address: 10.0.1.11, port_value: 8080 } } }
- endpoint: { address: { socket_address: { address: 10.0.1.12, port_value: 8080 } } }Mechanics
The exact knobs
| Knob | Product | Default | What it controls |
|---|---|---|---|
proxy_connect_timeout | NGINX | 60s | Time to establish the upstream connection; cannot usually exceed 75 s |
proxy_send_timeout | NGINX | 60s | Gap between two write operations to the upstream |
proxy_read_timeout | NGINX | 60s | Gap between two read operations from the upstream |
proxy_http_version | NGINX | 1.1 since 1.29.7, 1.0 before | HTTP version to the upstream; keepalive needs 1.1 |
proxy_request_buffering | NGINX | on | Read the whole request body before contacting the upstream |
proxy_buffering | NGINX | on | Buffer the upstream response before sending it to the client |
proxy_next_upstream | NGINX | error timeout | Which failures pass the request to the next server; POST/PATCH/LOCK only with non_idempotent |
client_max_body_size | NGINX | 1m | Maximum request body; larger gives 413 |
timeout connect/client/server | HAProxy | unset (set them) | Per-phase timers; timeout tunnel for upgraded connections |
option forwardfor | HAProxy | off | Adds X-Forwarded-For |
use_remote_address | Envoy | false | Trust the TCP peer, not the client's XFF, as the client address |
xff_num_trusted_hops | Envoy | 0 | Number of trusted proxies in front of the edge |
routing.http.xff_header_processing.mode | AWS ALB | append | Append, preserve or remove X-Forwarded-For |
| idle timeout | AWS ALB | 60 s | Close a connection idle in both directions |
MaxIdleConnsPerHost | Go http.Transport | 2 | Idle upstream connections per host; raise it for a proxy |
FlushInterval | Go httputil.ReverseProxy | 0 | How often to flush while copying the response; negative flushes immediately |
Status codes a proxy produces
| Status | Meaning | Typical cause | Retry? |
|---|---|---|---|
| 400 | Proxy could not parse the request | Bad header, request smuggling attempt | No |
| 407 | Proxy authentication required | Forward proxy without credentials | After adding credentials |
| 408 | Client too slow sending the request | Mobile network, slowloris | Yes, the client decides |
| 413 | Body larger than the proxy limit | client_max_body_size | No, change the request |
| 429 | Rate limit at the proxy | limit_req, WAF rule | After backoff (Retry-After) |
| 499 | NGINX-only: client closed the connection | User navigated away, client timeout shorter than proxy | No |
| 502 Bad Gateway | Invalid response or connection failure to the upstream | Refused, reset, crash, protocol mismatch | Idempotent only |
| 503 | No upstream available or deliberately shedding | All ejected, maintenance mode | Yes with backoff |
| 504 Gateway Timeout | Upstream did not answer in time | Slow query, long export, GC pause | Outcome unknown; idempotent only |
Log lines you will actually see
| Where | Line | Meaning |
|---|---|---|
| NGINX error log | connect() failed (111: Connection refused) while connecting to upstream | Nothing listens on the upstream port: 502 |
| NGINX error log | upstream timed out (110: Connection timed out) while reading response header from upstream | proxy_read_timeout fired: 504 |
| NGINX error log | upstream prematurely closed connection while reading response header from upstream | Upstream closed (crash, idle keepalive race): 502 |
| NGINX error log | no live upstreams while connecting to upstream | Every server in the group is marked down: 502 |
| NGINX error log | upstream sent too big header while reading response header from upstream | Response header larger than proxy_buffer_size: 502 |
| NGINX error log | client intended to send too large body | Body above client_max_body_size: 413 |
| HAProxy log | termination flags sH, sC, SC, cD | Server timeout waiting for headers, server timeout connecting, server refused, client timeout in data phase |
| Envoy access log | response flags UF, UT, UC, NR | Upstream connection failure, upstream request timeout, upstream connection termination, no route |
| Go proxy | http: proxy error: dial tcp 10.0.1.11:8080: connect: connection refused | The default ErrorHandler message when the upstream is down |
The client address arithmetic
1 header at the app: X-Forwarded-For: 203.0.113.99, 198.51.100.7, 10.0.0.4
2 TCP peer: 10.0.0.9 (trusted: in 10.0.0.0/8)
3 walk from the right: 10.0.0.4 trusted proxy -> skip
4 198.51.100.7 not a trusted proxy -> this is the client
5 everything left of it is the client's own claim -> ignore
6 untrusted peer: if the peer is not in the list, ignore the header entirely and use the peerWhat a request costs
Back-of-envelope, labelled as estimate: a proxy hop inside one availability zone adds roughly 0.1 to 1 ms of latency and a few percent CPU; a new TLS 1.3 connection costs one round trip plus public-key operations; so a proxy terminating TLS for clients far away (50 ms RTT) saves the application tier every handshake and keeps a warm pool (RTT 0.5 ms) to it. The number to remember is the ratio: handshakes at the edge are paid by the proxy once per client connection; handshakes upstream are paid once per pooled connection, not once per request.
Go
Example: a reverse proxy, a client-address resolver and a forward proxy
The Go code is three small packages and their tests. before is the naive client-IP function that trusts the first X-Forwarded-For entry (bad design, shown above). clientip is the right-to-left walk. rproxy builds on httputil.ReverseProxy with Rewrite (not the deprecated Director). fproxy is a forward proxy with CONNECT.
package clientip
import (
"net/http"
"net/netip"
"testing"
"academy/proxies-forward-reverse/before"
)
func TestFromRequest(t *testing.T) {
trusted, err := Parse("10.0.0.0/8", "192.0.2.10")
if err != nil {
t.Fatal(err)
}
cases := []struct {
name string
remote string
xff []string
want string
}{
{"direct client ignores header", "198.51.100.7:5000", []string{"203.0.113.99"}, "198.51.100.7"},
{"one trusted proxy", "10.0.0.5:4444", []string{"198.51.100.7"}, "198.51.100.7"},
{"two trusted hops", "10.0.0.5:4444", []string{"198.51.100.7, 10.1.1.1"}, "198.51.100.7"},
{"client forged the left side", "10.0.0.5:4444", []string{"203.0.113.99, 198.51.100.7"}, "198.51.100.7"},
{"split header lines", "10.0.0.5:4444", []string{"203.0.113.99", "198.51.100.7"}, "198.51.100.7"},
{"garbage entry stops the walk", "10.0.0.5:4444", []string{"not-an-ip, 10.9.9.9"}, "10.9.9.9"},
{"all hops trusted", "10.0.0.5:4444", []string{"10.2.2.2"}, "10.2.2.2"},
{"ipv6 mapped peer", "[::ffff:10.0.0.5]:80", []string{"2001:db8::1"}, "2001:db8::1"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, ok := FromRequest(c.remote, c.xff, trusted)
if !ok || got != netip.MustParseAddr(c.want) {
t.Fatalf("got %v ok=%v want %s", got, ok, c.want)
}
})
}
}
func TestNaiveVersionIsSpoofable(t *testing.T) {
r, _ := http.NewRequest(http.MethodGet, "http://example.test/", nil)
r.RemoteAddr = "198.51.100.7:5000"
r.Header.Set("X-Forwarded-For", "203.0.113.99")
if got := before.ClientIP(r); got != "203.0.113.99" {
t.Fatalf("expected the naive version to be fooled, got %s", got)
}
trusted, _ := Parse("10.0.0.0/8")
got, _ := FromRequest(r.RemoteAddr, r.Header.Values("X-Forwarded-For"), trusted)
if got.String() != "198.51.100.7" {
t.Fatalf("trusted-proxy version must ignore the header, got %s", got)
}
}// Package rproxy is a small reverse proxy built on httputil.ReverseProxy.
//
// It shows the decisions a real edge proxy makes: which forwarding headers
// to trust, how to bound every phase with a timeout, how to retry safely,
// how to map upstream failures to 502 and 504, and how to eject a dead upstream.
package rproxy
import (
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httputil"
"net/netip"
"net/url"
"sync"
"time"
"academy/proxies-forward-reverse/clientip"
)
// Config holds everything the proxy needs.
type Config struct {
Upstreams []*url.URL
TrustedProxies []netip.Prefix // peers whose X-Forwarded-* headers we believe
Pseudonym string // name written into the Via header
DialTimeout time.Duration // like nginx proxy_connect_timeout
ResponseHeaderTimeout time.Duration // time to first response byte, like proxy_read_timeout for the header
MaxAttempts int // total tries for a retryable request
EjectFor time.Duration // how long a failing upstream sits out
}
// Proxy is an http.Handler plus the upstream pool behind it.
type Proxy struct {
handler http.Handler
pool *pool
}
// New builds the proxy.
func New(cfg Config) (*Proxy, error) {
if len(cfg.Upstreams) == 0 {
return nil, errors.New("rproxy: no upstreams")
}
if cfg.DialTimeout == 0 {
cfg.DialTimeout = 3 * time.Second
}
if cfg.ResponseHeaderTimeout == 0 {
cfg.ResponseHeaderTimeout = 30 * time.Second
}
if cfg.MaxAttempts == 0 {
cfg.MaxAttempts = 2
}
if cfg.EjectFor == 0 {
cfg.EjectFor = 10 * time.Second
}
if cfg.Pseudonym == "" {
cfg.Pseudonym = "edge"
}
p := &Proxy{pool: newPool(cfg.Upstreams, cfg.EjectFor)}
base := &http.Transport{
DialContext: (&net.Dialer{Timeout: cfg.DialTimeout, KeepAlive: 30 * time.Second}).DialContext,
MaxIdleConns: 256,
MaxIdleConnsPerHost: 64, // keepalive upstream: reuse connections instead of one dial per request
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: cfg.ResponseHeaderTimeout,
ForceAttemptHTTP2: false, // HTTP/1.1 upstream; the client side may still speak HTTP/2
}
rp := &httputil.ReverseProxy{
Rewrite: func(pr *httputil.ProxyRequest) { rewrite(pr, cfg) },
Transport: &retryTransport{base: base, pool: p.pool, attempts: cfg.MaxAttempts},
ErrorHandler: errorHandler,
ModifyResponse: func(resp *http.Response) error { resp.Header.Add("Via", "1.1 "+cfg.Pseudonym); return nil },
FlushInterval: -1, // flush immediately: needed for SSE and streaming responses
}
p.handler = rp
return p, nil
}
// ServeHTTP implements http.Handler.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) { p.handler.ServeHTTP(w, r) }
// rewrite builds the outbound request. ReverseProxy has already removed
// hop-by-hop headers and the Forwarded / X-Forwarded-* headers from Out.
func rewrite(pr *httputil.ProxyRequest, cfg Config) {
in, out := pr.In, pr.Out
peerTrusted := false
if peer, ok := clientip.PeerAddr(in.RemoteAddr); ok {
peerTrusted = clientip.Trusted(peer, cfg.TrustedProxies)
}
if peerTrusted {
// An upstream proxy of ours spoke: keep its chain and append the peer.
out.Header["X-Forwarded-For"] = in.Header["X-Forwarded-For"]
}
pr.SetXForwarded() // appends the peer address, sets X-Forwarded-Host and X-Forwarded-Proto
if peerTrusted {
if proto := in.Header.Get("X-Forwarded-Proto"); proto != "" {
out.Header.Set("X-Forwarded-Proto", proto) // TLS ended at the tier before us
}
}
out.Header.Del("X-Real-IP") // never forward a value the client could have set
if ip, ok := clientip.FromRequest(in.RemoteAddr, in.Header.Values("X-Forwarded-For"), cfg.TrustedProxies); ok {
out.Header.Set("X-Real-IP", ip.String())
}
out.Header.Add("Via", fmt.Sprintf("%d.%d %s", in.ProtoMajor, in.ProtoMinor, cfg.Pseudonym))
// Host is preserved (out is a clone of in), so the app sees the public host name.
}
// errorHandler maps proxy failures to the status codes RFC 9110 defines.
func errorHandler(w http.ResponseWriter, r *http.Request, err error) {
var ne net.Error
switch {
case errors.Is(err, context.Canceled):
w.WriteHeader(499) // client went away; nginx logs the same non-standard code
case errors.Is(err, context.DeadlineExceeded), errors.As(err, &ne) && ne.Timeout():
http.Error(w, "upstream timed out", http.StatusGatewayTimeout) // 504
default:
http.Error(w, "bad gateway", http.StatusBadGateway) // 502: refused, reset, invalid response
}
}
// retryTransport picks an upstream per attempt and retries only when that is safe.
type retryTransport struct {
base http.RoundTripper
pool *pool
attempts int
}
func (t *retryTransport) RoundTrip(req *http.Request) (*http.Response, error) {
var lastErr error
for i := 0; i < t.attempts; i++ {
up := t.pool.pick()
if up == nil {
return nil, errors.New("rproxy: no healthy upstream")
}
out := req.Clone(req.Context())
out.URL.Scheme, out.URL.Host = up.url.Scheme, up.url.Host
resp, err := t.base.RoundTrip(out)
if err == nil {
return resp, nil
}
lastErr = err
if !retryable(req, err) {
return nil, err
}
t.pool.eject(up) // the connection never opened: take this upstream out for a while
}
return nil, lastErr
}
// retryable allows a retry only for idempotent requests without a body, and
// only when the failure happened while dialing, so no byte reached the upstream.
func retryable(req *http.Request, err error) bool {
switch req.Method {
case http.MethodGet, http.MethodHead, http.MethodOptions:
default:
return false
}
if req.Body != nil && req.Body != http.NoBody {
return false
}
var oe *net.OpError
return errors.As(err, &oe) && oe.Op == "dial"
}
type upstream struct {
url *url.URL
downUntil time.Time
}
type pool struct {
mu sync.Mutex
ups []*upstream
next int
ejectFor time.Duration
}
func newPool(urls []*url.URL, ejectFor time.Duration) *pool {
p := &pool{ejectFor: ejectFor}
for _, u := range urls {
p.ups = append(p.ups, &upstream{url: u})
}
return p
}
// pick is round robin over upstreams that are not ejected. If all are
// ejected it still returns one, so a bad health signal cannot cause a total outage.
func (p *pool) pick() *upstream {
p.mu.Lock()
defer p.mu.Unlock()
now := time.Now()
for i := 0; i < len(p.ups); i++ {
u := p.ups[(p.next+i)%len(p.ups)]
if now.After(u.downUntil) {
p.next = (p.next + i + 1) % len(p.ups)
return u
}
}
u := p.ups[p.next%len(p.ups)]
p.next++
return u
}
func (p *pool) eject(u *upstream) {
p.mu.Lock()
u.downUntil = time.Now().Add(p.ejectFor)
p.mu.Unlock()
}
func (p *pool) set(u *upstream, up bool) {
p.mu.Lock()
if up {
u.downUntil = time.Time{}
} else {
u.downUntil = time.Now().Add(p.ejectFor)
}
p.mu.Unlock()
}
// CheckLoop probes GET /healthz on every upstream until ctx ends (active health check).
func (p *Proxy) CheckLoop(ctx context.Context, every time.Duration) {
client := &http.Client{Timeout: time.Second}
t := time.NewTicker(every)
defer t.Stop()
for {
for _, u := range p.pool.ups {
ok := false
if resp, err := client.Get(u.url.String() + "/healthz"); err == nil {
ok = resp.StatusCode == http.StatusOK
resp.Body.Close()
}
p.pool.set(u, ok)
}
select {
case <-ctx.Done():
return
case <-t.C:
}
}
}
// Healthy reports how many upstreams are currently in rotation.
func (p *Proxy) Healthy() int {
p.pool.mu.Lock()
defer p.pool.mu.Unlock()
n := 0
for _, u := range p.pool.ups {
if time.Now().After(u.downUntil) {
n++
}
}
return n
}package rproxy
import (
"bufio"
"context"
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
"academy/proxies-forward-reverse/clientip"
)
func mustURL(t *testing.T, s string) *url.URL {
t.Helper()
u, err := url.Parse(s)
if err != nil {
t.Fatal(err)
}
return u
}
// echoHeaders replies with the headers the upstream saw.
func echoHeaders(w http.ResponseWriter, r *http.Request) {
for _, k := range []string{"X-Forwarded-For", "X-Forwarded-Proto", "X-Forwarded-Host", "X-Real-Ip", "Via", "Connection", "Keep-Alive"} {
w.Header().Set("Seen-"+k, r.Header.Get(k))
}
w.Header().Set("Seen-Host", r.Host)
}
func newProxy(t *testing.T, cfg Config) *httptest.Server {
t.Helper()
p, err := New(cfg)
if err != nil {
t.Fatal(err)
}
srv := httptest.NewServer(p)
t.Cleanup(srv.Close)
return srv
}
func TestUntrustedClientCannotForgeForwardingHeaders(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(echoHeaders))
defer up.Close()
srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, Pseudonym: "edge-1"})
req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
req.Header.Set("X-Forwarded-For", "203.0.113.99")
req.Header.Set("X-Forwarded-Proto", "https")
req.Header.Set("X-Real-IP", "203.0.113.99")
req.Header.Set("Connection", "keep-alive, X-Secret")
req.Header.Set("X-Secret", "hop")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if got := resp.Header.Get("Seen-X-Forwarded-For"); got != "127.0.0.1" {
t.Fatalf("XFF must hold only the peer, got %q", got)
}
if got := resp.Header.Get("Seen-X-Forwarded-Proto"); got != "http" {
t.Fatalf("proto must be what this hop saw, got %q", got)
}
if got := resp.Header.Get("Seen-X-Real-Ip"); got != "127.0.0.1" {
t.Fatalf("X-Real-IP must be recomputed, got %q", got)
}
if got := resp.Header.Get("Seen-Via"); !strings.HasSuffix(got, " edge-1") {
t.Fatalf("Via missing: %q", got)
}
if got := resp.Header.Get("Via"); !strings.HasSuffix(got, " edge-1") {
t.Fatalf("response Via missing: %q", got)
}
}
func TestTrustedPeerChainIsKept(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(echoHeaders))
defer up.Close()
trusted, _ := clientip.Parse("127.0.0.0/8")
srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, TrustedProxies: trusted})
req, _ := http.NewRequest(http.MethodGet, srv.URL, nil)
req.Header.Set("X-Forwarded-For", "198.51.100.7")
req.Header.Set("X-Forwarded-Proto", "https")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if got := resp.Header.Get("Seen-X-Forwarded-For"); got != "198.51.100.7, 127.0.0.1" {
t.Fatalf("chain: %q", got)
}
if got := resp.Header.Get("Seen-X-Forwarded-Proto"); got != "https" {
t.Fatalf("proto: %q", got)
}
if got := resp.Header.Get("Seen-X-Real-Ip"); got != "198.51.100.7" {
t.Fatalf("real ip: %q", got)
}
}
func deadURL(t *testing.T) *url.URL {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
addr := l.Addr().String()
l.Close() // nothing listens here any more: connection refused
return mustURL(t, "http://"+addr)
}
func TestRetryOnDialFailureForGET(t *testing.T) {
good := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }))
defer good.Close()
srv := newProxy(t, Config{Upstreams: []*url.URL{deadURL(t), mustURL(t, good.URL)}, MaxAttempts: 2})
for i := 0; i < 4; i++ { // round robin hits the dead upstream first on some requests
resp, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
b, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode != 200 || string(b) != "ok" {
t.Fatalf("request %d: %d %q", i, resp.StatusCode, b)
}
}
}
func TestNoRetryForPOSTReturns502(t *testing.T) {
srv := newProxy(t, Config{Upstreams: []*url.URL{deadURL(t)}, MaxAttempts: 3})
resp, err := http.Post(srv.URL, "text/plain", strings.NewReader("x"))
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadGateway {
t.Fatalf("want 502, got %d", resp.StatusCode)
}
}
func TestSlowUpstreamReturns504(t *testing.T) {
slow := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
select {
case <-time.After(2 * time.Second):
case <-r.Context().Done():
}
}))
defer slow.Close()
srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, slow.URL)}, ResponseHeaderTimeout: 100 * time.Millisecond})
resp, err := http.Get(srv.URL)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusGatewayTimeout {
t.Fatalf("want 504, got %d", resp.StatusCode)
}
}
func TestActiveHealthCheckEjectsFailingUpstream(t *testing.T) {
var healthy atomic.Bool
healthy.Store(true)
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/healthz" && !healthy.Load() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
io.WriteString(w, "ok")
}))
defer up.Close()
p, err := New(Config{Upstreams: []*url.URL{mustURL(t, up.URL)}, EjectFor: time.Minute})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
healthy.Store(false)
go p.CheckLoop(ctx, 20*time.Millisecond)
deadline := time.Now().Add(2 * time.Second)
for p.Healthy() != 0 && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
if p.Healthy() != 0 {
t.Fatal("upstream should have been ejected")
}
}
// TestUpgradeIsTunnelled shows that ReverseProxy handles 101 Switching Protocols:
// Connection and Upgrade are hop-by-hop, yet the proxy re-adds them for the upstream.
func TestUpgradeIsTunnelled(t *testing.T) {
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.EqualFold(r.Header.Get("Upgrade"), "echo") {
http.Error(w, "no upgrade", http.StatusBadRequest)
return
}
conn, rw, err := w.(http.Hijacker).Hijack()
if err != nil {
return
}
defer conn.Close()
rw.WriteString("HTTP/1.1 101 Switching Protocols\r\nUpgrade: echo\r\nConnection: Upgrade\r\n\r\n")
rw.Flush()
buf := make([]byte, 4)
if _, err := io.ReadFull(rw, buf); err == nil {
conn.Write(buf)
}
}))
defer up.Close()
srv := newProxy(t, Config{Upstreams: []*url.URL{mustURL(t, up.URL)}})
conn, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://"))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
conn.SetDeadline(time.Now().Add(3 * time.Second))
io.WriteString(conn, "GET /ws HTTP/1.1\r\nHost: example.test\r\nConnection: Upgrade\r\nUpgrade: echo\r\n\r\n")
br := bufio.NewReader(conn)
resp, err := http.ReadResponse(br, nil)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != http.StatusSwitchingProtocols {
t.Fatalf("want 101, got %d", resp.StatusCode)
}
io.WriteString(conn, "ping")
got := make([]byte, 4)
if _, err := io.ReadFull(br, got); err != nil || string(got) != "ping" {
t.Fatalf("echo through tunnel failed: %q %v", got, err)
}
}// Package fproxy is a minimal forward (egress) proxy: it answers CONNECT for
// HTTPS tunnels and absolute-form requests for plain HTTP, and applies an
// allow-list so servers can only reach destinations someone approved.
package fproxy
import (
"crypto/subtle"
"io"
"net"
"net/http"
"strings"
"sync"
"time"
)
// Proxy is an http.Handler for clients configured with this proxy.
type Proxy struct {
Allow func(hostport string) bool // egress policy; nil denies everything
Credentials string // "user:pass" for Basic proxy auth; empty disables auth
DialTimeout time.Duration
Transport *http.Transport // used for plain HTTP; nil means a default with Proxy disabled
once sync.Once
}
// hopByHop lists the headers a proxy must not forward (RFC 9110 section 7.6.1 plus legacy names).
var hopByHop = []string{
"Connection", "Proxy-Connection", "Keep-Alive", "Proxy-Authenticate",
"Proxy-Authorization", "Te", "Trailer", "Transfer-Encoding", "Upgrade",
}
// RemoveHopByHop deletes the standard hop-by-hop headers and every header named in Connection.
func RemoveHopByHop(h http.Header) {
for _, v := range h.Values("Connection") {
for _, name := range strings.Split(v, ",") {
if name = strings.TrimSpace(name); name != "" {
h.Del(name)
}
}
}
for _, name := range hopByHop {
h.Del(name)
}
}
func (p *Proxy) init() {
p.once.Do(func() {
if p.DialTimeout == 0 {
p.DialTimeout = 5 * time.Second
}
if p.Transport == nil {
p.Transport = &http.Transport{Proxy: nil, MaxIdleConnsPerHost: 16, IdleConnTimeout: 90 * time.Second}
}
})
}
func (p *Proxy) authorised(r *http.Request) bool {
if p.Credentials == "" {
return true
}
user, pass, ok := parseBasic(r.Header.Get("Proxy-Authorization"))
return ok && subtle.ConstantTimeCompare([]byte(user+":"+pass), []byte(p.Credentials)) == 1
}
func parseBasic(h string) (user, pass string, ok bool) {
// Reuse net/http's parser by wrapping the value in a throwaway request.
r := &http.Request{Header: http.Header{"Authorization": {h}}}
return r.BasicAuth()
}
// ServeHTTP implements http.Handler.
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
p.init()
if !p.authorised(r) {
w.Header().Set("Proxy-Authenticate", `Basic realm="egress"`)
http.Error(w, "proxy authentication required", http.StatusProxyAuthRequired) // 407
return
}
if r.Method == http.MethodConnect {
p.connect(w, r)
return
}
p.forward(w, r)
}
// connect opens a blind tunnel: after "200 Connection Established" the proxy
// only copies bytes, so TLS stays end to end between client and origin.
func (p *Proxy) connect(w http.ResponseWriter, r *http.Request) {
target := r.Host // authority-form: host:port
if p.Allow == nil || !p.Allow(target) {
http.Error(w, "destination not allowed", http.StatusForbidden)
return
}
upstream, err := net.DialTimeout("tcp", target, p.DialTimeout)
if err != nil {
http.Error(w, "cannot reach destination", http.StatusBadGateway)
return
}
hj, ok := w.(http.Hijacker)
if !ok {
upstream.Close()
http.Error(w, "hijacking unsupported", http.StatusInternalServerError)
return
}
client, _, err := hj.Hijack()
if err != nil {
upstream.Close()
return
}
io.WriteString(client, "HTTP/1.1 200 Connection Established\r\n\r\n")
var wg sync.WaitGroup
wg.Add(2)
pipe := func(dst, src net.Conn) {
defer wg.Done()
io.Copy(dst, src)
if tc, ok := dst.(*net.TCPConn); ok {
tc.CloseWrite() // propagate half-close so the peer sees EOF
}
}
go pipe(upstream, client)
go pipe(client, upstream)
wg.Wait()
client.Close()
upstream.Close()
}
// forward handles absolute-form requests such as "GET http://host/path HTTP/1.1".
func (p *Proxy) forward(w http.ResponseWriter, r *http.Request) {
if !r.URL.IsAbs() {
http.Error(w, "a forward proxy needs an absolute-form request target", http.StatusBadRequest)
return
}
if p.Allow == nil || !p.Allow(r.URL.Host) {
http.Error(w, "destination not allowed", http.StatusForbidden)
return
}
out := r.Clone(r.Context())
out.RequestURI = ""
RemoveHopByHop(out.Header)
out.Header.Add("Via", "1.1 egress")
resp, err := p.Transport.RoundTrip(out)
if err != nil {
http.Error(w, "bad gateway", http.StatusBadGateway)
return
}
defer resp.Body.Close()
RemoveHopByHop(resp.Header)
for k, vs := range resp.Header {
for _, v := range vs {
w.Header().Add(k, v)
}
}
w.Header().Add("Via", "1.1 egress")
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
}package fproxy
import (
"io"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestRemoveHopByHop(t *testing.T) {
h := http.Header{}
h.Set("Connection", "close, X-Private")
h.Set("X-Private", "1")
h.Set("Keep-Alive", "timeout=5")
h.Set("Proxy-Authorization", "Basic abc")
h.Set("Accept", "text/html")
RemoveHopByHop(h)
if len(h) != 1 || h.Get("Accept") == "" {
t.Fatalf("only end-to-end headers may remain: %v", h)
}
}
func startEcho(t *testing.T) string {
t.Helper()
l, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() { defer c.Close(); io.Copy(c, c) }()
}
}()
return l.Addr().String()
}
func TestConnectTunnelsBytes(t *testing.T) {
echo := startEcho(t)
proxy := httptest.NewServer(&Proxy{Allow: func(hp string) bool { return hp == echo }})
defer proxy.Close()
c, err := net.Dial("tcp", strings.TrimPrefix(proxy.URL, "http://"))
if err != nil {
t.Fatal(err)
}
defer c.Close()
c.SetDeadline(time.Now().Add(3 * time.Second))
io.WriteString(c, "CONNECT "+echo+" HTTP/1.1\r\nHost: "+echo+"\r\n\r\n")
buf := make([]byte, len("HTTP/1.1 200 Connection Established\r\n\r\n"))
if _, err := io.ReadFull(c, buf); err != nil || !strings.HasPrefix(string(buf), "HTTP/1.1 200") {
t.Fatalf("handshake: %q %v", buf, err)
}
io.WriteString(c, "hello")
got := make([]byte, 5)
if _, err := io.ReadFull(c, got); err != nil || string(got) != "hello" {
t.Fatalf("tunnel echo: %q %v", got, err)
}
}
func TestConnectDeniedByPolicy(t *testing.T) {
proxy := httptest.NewServer(&Proxy{Allow: func(string) bool { return false }})
defer proxy.Close()
c, _ := net.Dial("tcp", strings.TrimPrefix(proxy.URL, "http://"))
defer c.Close()
io.WriteString(c, "CONNECT 203.0.113.9:443 HTTP/1.1\r\nHost: 203.0.113.9:443\r\n\r\n")
b := make([]byte, 12)
io.ReadFull(c, b)
if !strings.HasPrefix(string(b), "HTTP/1.1 403") {
t.Fatalf("want 403, got %q", b)
}
}
func TestPlainHTTPThroughProxyAddsVia(t *testing.T) {
origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Saw-Via", r.Header.Get("Via"))
w.Header().Set("X-Saw-Proxy-Auth", r.Header.Get("Proxy-Authorization"))
io.WriteString(w, "origin")
}))
defer origin.Close()
host := strings.TrimPrefix(origin.URL, "http://")
proxy := httptest.NewServer(&Proxy{Allow: func(hp string) bool { return hp == host }, Credentials: "svc:s3cret"})
defer proxy.Close()
pu, _ := url.Parse(proxy.URL)
pu.User = url.UserPassword("svc", "s3cret")
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
resp, err := client.Get(origin.URL)
if err != nil {
t.Fatal(err)
}
body, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if string(body) != "origin" || resp.Header.Get("X-Saw-Via") != "1.1 egress" {
t.Fatalf("body=%q via=%q", body, resp.Header.Get("X-Saw-Via"))
}
if resp.Header.Get("X-Saw-Proxy-Auth") != "" {
t.Fatal("proxy credentials must never reach the origin")
}
}
func TestMissingCredentialsGets407(t *testing.T) {
proxy := httptest.NewServer(&Proxy{Credentials: "svc:s3cret", Allow: func(string) bool { return true }})
defer proxy.Close()
pu, _ := url.Parse(proxy.URL)
client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(pu)}}
resp, err := client.Get("http://198.51.100.1/")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusProxyAuthRequired || resp.Header.Get("Proxy-Authenticate") == "" {
t.Fatalf("want 407 with Proxy-Authenticate, got %d", resp.StatusCode)
}
}
func TestOriginFormRequestIsRejected(t *testing.T) {
proxy := httptest.NewServer(&Proxy{Allow: func(string) bool { return true }})
defer proxy.Close()
resp, err := http.Get(proxy.URL + "/not-absolute")
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("want 400, got %d", resp.StatusCode)
}
}The Go angle
httputil.ReverseProxyhas two ways to rewrite a request.Directoris deprecated;Rewritereceives aProxyRequestwithIn(read only) andOut, and the library removes hop-by-hop headers and theForwarded,X-Forwarded-For,X-Forwarded-HostandX-Forwarded-Protoheaders fromOutbefore calling it. That default is the safe one: nothing the client sent survives unless you copy it, asrproxydoes only for trusted peers.ProxyRequest.SetXForwarded()writesX-Forwarded-For(appending the client IP to an existing value),X-Forwarded-HostandX-Forwarded-Proto;SetURLrewrites the target and the Host header. CopyIn.Header["X-Forwarded-For"]intoOutfirst if and only if the peer is a trusted proxy.- The proxy and its transport are separate objects. Put policy (retry, ejection, timeouts) in a
RoundTripperand keepReverseProxyfor header and error mapping.ErrorHandleris where 502 and 504 are decided; the default is 502 for everything, so timeouts need explicit handling. - A proxy needs a tuned
http.Transport:MaxIdleConnsPerHost(default 2),IdleConnTimeout,ResponseHeaderTimeout, anet.Dialertimeout. Do not usehttp.DefaultTransportin a proxy. - Streaming:
FlushInterval: -1flushes after every write; the documentation saysFlushIntervalis ignored for responses the proxy recognises as streaming and for unknown content length, which are flushed immediately. - Upgrades:
ReverseProxydetectsConnection: Upgradeand handles101 Switching Protocolsby hijacking both connections. The test shows an echo through it. - A forward proxy in Go needs
http.Hijackerfor CONNECT andCloseWriteon*net.TCPConnfor half-close. HTTP/2 servers cannot hijack; serve the proxy listener with HTTP/1.1. - Behind a proxy, a Go server reads the client address with its own
clientip.FromRequest;r.RemoteAddris the proxy.http.Serverhas no built-in trusted-proxy logic. - Graceful shutdown:
srv.Shutdown(ctx)stops accepting and waits for active requests; hijacked connections (WebSocket, CONNECT tunnels) are not tracked by Shutdown, so close them yourself.
Laravel
Example: trusted proxies, URL generation behind TLS termination, Octane behind NGINX
The bootstrap file above trusts only the proxy ranges from TRUSTED_PROXIES, trusts only the headers the edge really sets, and restricts the Host header with trustHosts. The controller and the feature test below show and prove the behaviour. The Octane NGINX configuration from the Laravel documentation is the reference for a long-running application server behind a reverse proxy: it serves static files from NGINX, proxies the rest to the Octane server on port 8000, sends Host, X-Forwarded-For, Upgrade and Connection headers with an $connection_upgrade map.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class WhoAmIController extends Controller
{
/**
* Shows what the application believes about the request after TrustProxies ran.
* Behind a trusted proxy these values come from X-Forwarded-*; from anyone else they
* come from the TCP connection and the headers are ignored.
*/
public function __invoke(Request $request): JsonResponse
{
return response()->json([
'ip' => $request->ip(), // the client address after proxy resolution
'ips' => $request->ips(), // every client address Laravel found in the forwarded chain (order: see the Laravel docs)
'secure' => $request->isSecure(), // true when X-Forwarded-Proto: https is trusted
'host' => $request->getHost(), // from X-Forwarded-Host when trusted
'root' => $request->root(), // base of generated absolute URLs
'login_url' => route('login'), // https://app.example.com/login behind TLS termination
'server_remote_addr' => $request->server('REMOTE_ADDR'), // the proxy itself
]);
}
}<?php
namespace Tests\Feature;
use Tests\TestCase;
class TrustProxiesTest extends TestCase
{
public function test_trusted_proxy_headers_are_applied(): void
{
// REMOTE_ADDR is inside TRUSTED_PROXIES, so X-Forwarded-* is believed.
$response = $this->withServerVariables(['REMOTE_ADDR' => '10.0.0.5'])
->withHeaders([
'X-Forwarded-For' => '198.51.100.7',
'X-Forwarded-Proto' => 'https',
'X-Forwarded-Host' => 'app.example.com',
])
->getJson('/whoami');
$response->assertOk()->assertJson([
'ip' => '198.51.100.7',
'secure' => true,
'host' => 'app.example.com',
]);
}
public function test_untrusted_peer_cannot_forge_the_client_address(): void
{
// A direct client (outside TRUSTED_PROXIES) sends a forged header.
$response = $this->withServerVariables(['REMOTE_ADDR' => '203.0.113.50'])
->withHeaders(['X-Forwarded-For' => '10.1.2.3', 'X-Forwarded-Proto' => 'https'])
->getJson('/whoami');
$response->assertOk()->assertJson([
'ip' => '203.0.113.50',
'secure' => false,
]);
}
}<?php
namespace App\Services;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
/**
* Outbound calls from the application go through the company forward proxy.
* "proxy" and "no" are Guzzle request options, passed with withOptions().
*/
class EgressClient
{
public function make(): PendingRequest
{
return Http::withOptions([
'proxy' => [
'http' => (string) config('services.egress.http'), // e.g. http://svc:secret@egress.internal.example:3128
'https' => (string) config('services.egress.https'), // HTTPS is tunnelled with CONNECT
'no' => ['.internal.example', 'localhost', '127.0.0.1'], // never proxy internal destinations
],
])->connectTimeout(3)->timeout(10)->retry(2, 200, throw: false);
}
}The Laravel angle
Illuminate\Http\Middleware\TrustProxiesis configured inbootstrap/app.phpwith$middleware->trustProxies(at: ..., headers: ...). The Laravel documentation says the symptom of not doing so is that theurlhelper does not generate HTTPS links behind a load balancer that terminates TLS.at: '*'trusts every peer. The documentation offers it for cloud load balancers whose addresses are unknown; only use it when the application cannot be reached except through the balancer (private subnet, security group that allows only the balancer).- The
headersargument picks which headers are believed:Request::HEADER_X_FORWARDED_FOR | HEADER_X_FORWARDED_HOST | HEADER_X_FORWARDED_PORT | HEADER_X_FORWARDED_PROTO,HEADER_X_FORWARDED_AWS_ELBfor AWS Elastic Load Balancing,HEADER_FORWARDEDfor a balancer that sends the RFC 7239 header. - After TrustProxies,
$request->ip(),$request->ips(),$request->isSecure(),$request->getHost(),url(),route()and signed URL validation use the forwarded values. Signed URLs fail validation if the host or scheme differ between signing and verification, a common symptom of a missing proxy trust. trustHosts(at: [...])(theTrustHostsmiddleware) rejects requests whose Host header is not on the list; it matters because the Host header (or X-Forwarded-Host when trusted) builds absolute URLs, password reset links included.- Rate limiters key by
$request->ip(). Behind an untrusted proxy setup every user shares the balancer's address and a limit of 60 per minute locks everybody out at once; see the Laravel rate limiting in Rate Limiting Algorithms. - Outbound:
Http::withOptions([...])passes Guzzle request options; the Guzzleproxyoption takes a string or an array per scheme with anolist, and CONNECT is used for HTTPS targets. - Octane: FrankenPHP, RoadRunner or Swoole serve the app; Laravel's documentation says to serve production Octane behind a traditional web server, which will "serve your static assets such as images and stylesheets, as well as manage your SSL certificate termination". Since the app sees the proxy as peer, TrustProxies applies exactly as with FPM.
- PHP-FPM behind NGINX is a reverse proxy relationship too, using FastCGI (
fastcgi_pass) instead ofproxy_pass; the same timeouts exist asfastcgi_read_timeout.
-- Request log with both addresses, to catch a misconfigured trust list
CREATE TABLE http_access (
at timestamptz NOT NULL DEFAULT now(),
peer_addr inet NOT NULL, -- TCP peer (the proxy) = REMOTE_ADDR
client_addr inet NOT NULL, -- address the app resolved after TrustProxies
xff text, -- raw X-Forwarded-For for forensics
status smallint NOT NULL,
path text NOT NULL
);
-- If client_addr equals peer_addr for most rows behind a proxy, the trust list is wrong.
SELECT peer_addr, count(*) AS requests,
count(*) FILTER (WHERE client_addr = peer_addr) AS unresolved
FROM http_access
WHERE at > now() - interval '1 hour'
GROUP BY peer_addr
HAVING count(*) FILTER (WHERE client_addr = peer_addr) > 0.9 * count(*);Solving the classic problems
Every user appears to come from the load balancer
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
App reads REMOTE_ADDR | Trust the proxy and read the forwarded address (TrustProxies, set_real_ip_from) | Correct IPs in logs, limits, geo | Requires an accurate trusted list |
| L4 balancer hides the client | PROXY protocol v2 to the next tier | Works for any protocol | Both ends must agree |
| CDN in front | Trust the CDN ranges; read CF-Connecting-IP or XFF behind it | Real visitor IP | Maintain the CDN range list |
Redirect loop or http links behind HTTPS
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| App thinks the request is plain HTTP | Send X-Forwarded-Proto: https and trust it | Absolute URLs and redirects correct | Trust list needed |
| "HTTPS redirect" at both proxy and app | Redirect only at the outermost proxy | No loop | One owner of the rule |
Cookie Secure flag not set | Fix the scheme first, then secure cookies work | Session safety | None |
502 for a few hundred milliseconds on every deploy
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| App stopped before the proxy stopped sending | Readiness fails first, delay (preStop sleep), then SIGTERM, drain | Zero failed requests | Slower deploys |
| Idle keepalive race | Upstream idle timeout longer than proxy pool lifetime | No sporadic resets | Tune both ends |
| Retry disabled | proxy_next_upstream error timeout for idempotent requests | Hides the blip | POST not retried |
504 on long operations
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Endpoint needs more than the proxy read timeout | Make it asynchronous: 202 plus status resource | Scales, survives retries | Client code changes |
| Raising the timeout everywhere | Raise on one location only, keep the global tight | Contained | Still ties up a worker |
| Retry after 504 duplicates the work | Idempotency key | Safe | Storage for keys |
WebSocket drops at 60 seconds
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| Proxy idle timeout | Longer proxy_read_timeout / timeout tunnel and application pings | Stable connections | Idle sockets hold memory |
| Upgrade headers dropped | Set Upgrade and Connection explicitly | Handshake succeeds | Config per location |
| ALB idle timeout | Heartbeat shorter than the idle timeout | Works without config | Traffic overhead |
Slow uploads exhaust workers
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| App reads the body from the client directly | proxy_request_buffering on, body timeouts | Workers busy only when the body is complete | Disk or memory for buffers |
| Huge files | Direct-to-object-storage upload with a presigned URL | Bypasses the app tier | Extra flow |
Server-side request forgery through a fetching feature
| Cause | Fix | Advantage | Cost or limit |
|---|---|---|---|
| App fetches user-supplied URLs | Route through an egress proxy with an allow-list and a block on private ranges | Central enforcement | Proxy is a new dependency |
| DNS rebinding | Resolve once at the proxy and connect to that address | Closes the rebinding gap | Proxy must pin the IP |
Choosing
| Situation | Choose | Extra technique | Reason |
|---|---|---|---|
| Control or log outbound traffic from servers | Forward proxy (Squid or a managed gateway) with an allow-list | Network rule that blocks direct egress | An app-level setting can be removed by an attacker |
| Public website or API on a few servers | NGINX or Caddy as a reverse proxy | Tight timeouts, buffering, rate limit | Simple, fast, well known |
| TCP service (database, MQTT, SMTP) | L4 proxy (HAProxy mode tcp, NLB) | PROXY protocol v2 | No HTTP to parse |
| Backend must own the TLS key | TLS passthrough at an L4 proxy | SNI routing | Keys never leave the backend |
| Path or host routing, WAF, header logic | L7 reverse proxy (NGINX, HAProxy, Envoy, ALB) | Re-encrypt inside the VPC | HTTP awareness |
| Containers with changing addresses | Traefik, Envoy Gateway or a Kubernetes ingress controller | Provider based discovery | Config follows the platform |
| Service-to-service mTLS and retries | Sidecar mesh (Envoy under Istio or Linkerd) | Outlier detection | Uniform policy without code |
| Global traffic, DDoS, caching | Cloudflare or another CDN in front | Trust only its ranges at the origin | Absorbs attacks at the edge |
| Browsers must use the proxy | PAC or MDM-pushed settings | DIRECT for internal ranges | No manual client setup |
| Legacy non-HTTP client | SOCKS5 | Auth and allow-list | Protocol agnostic |
In architecture: from a single process to a distributed system
Monolith: one process, one database
One Laravel application on one VM: NGINX terminates TLS on 443, serves static files, and passes dynamic requests to PHP-FPM. There is a reverse proxy even here, and it already does the job that matters: it absorbs slow clients, enforces a body limit and writes the access log. TrustProxies is not needed yet (NGINX uses FastCGI and sets REMOTE_ADDR from the socket). The first time a cloud load balancer or CDN is put in front, REMOTE_ADDR becomes the balancer and the trusted-proxy configuration becomes the first thing to get right.
Modular monolith: boundaries without the network
Several modules in one deployable, but traffic arrives on several hostnames and paths (app.example.com, api.example.com, /admin). The proxy routes by host and path to separate pools of the same codebase (public, API, admin), which lets admin be restricted by network and API be rate limited differently, without splitting the code. Egress becomes a decision: the payment module and the webhook module call out, and a forward proxy with an allow-list is the cheapest control to stop one module from reaching what only the other may.
Microservices: every arrow is a decision
1 browser -> Cloudflare TLS, WAF, DDoS filtering; sets CF-Connecting-IP and X-Forwarded-For
2 Cloudflare -> AWS NLB TCP 443, passthrough to the proxy fleet
3 NLB -> Envoy edge fleet PROXY protocol v2 carries the Cloudflare address; Envoy terminates TLS
4 Envoy edge -> gateway L7 routing, JWT check, rate limit by resolved client address
5 gateway -> orders sidecar mTLS, retry policy, timeout 3 s
6 orders sidecar -> orders app plain localhost, X-Request-Id propagated
7 orders app -> egress proxy CONNECT api.carrier.example:443, allow-listed, loggedSeven hops, four different places that can mint or forward the client address. Each one needs a rule: who may set X-Forwarded-For, which header is authoritative at each tier, which timeout belongs to which hop (and they shrink inward), which tier retries. The common failure is a chain where each team trusts the previous tier's header without checking the previous tier is theirs. See Service Communication for budgets and Service Mesh & Sidecar for the east-west part.
Distributed data: replicas, caches, regions
Proxies appear in front of data too. A connection-pooling proxy (PgBouncer, ProxySQL) is an L7-ish proxy for the database wire protocol, covered in Connection Pooling; HAProxy in mode tcp fronting PostgreSQL replicas gives read/write splitting only if something decides which port is primary (see Replication, Read Replicas & Failover). A caching reverse proxy is a cache tier with the trade-offs in Caching: stale content, purge, cache keys that must include the variants (Accept-Encoding, language, cookies). Multi-region: a global proxy (Cloudflare, an anycast load balancer) steers by latency and health; see IP, DNS & GeoDNS. The client address is the first thing lost across regions, so carry it in the chain consistently.
Scaling path: 1x, 10x, 100x
| Load | Design | What breaks first | Fix |
|---|---|---|---|
| 1x: hundreds of requests per second | One NGINX in front of one app server | Single point of failure; slow uploads hold workers | Request buffering, a second app server |
| 10x: thousands of rps | Two NGINX or an ALB in front of a pool; keepalive upstream; health checks | Ephemeral port exhaustion to upstreams, idle-timeout races, wrong client IP | Keepalive pools, tuned timeouts, trusted proxies |
| 100x: tens of thousands of rps and multi-region | CDN and anycast edge, L4 tier plus L7 fleet, PROXY protocol, outlier detection, rate limits at the edge | Config sprawl, reload blast radius, certificate rotation, noisy neighbours | Dynamic config (xDS), progressive rollout, per-tenant limits, observability |
Lab: forging an address, then fixing it, with tests
All steps run on one machine with the Go toolchain; the NGINX and Laravel steps are expected output, not run (marked below).
- Run the Go tests, which exercise the forged-header case, the retry case, 502, 504, upgrade and CONNECT:
$ cd docs/snippets/system-design/proxies-forward-reverse/go
$ go test -race -count=1 ./...
? academy/proxies-forward-reverse/before [no test files]
? academy/proxies-forward-reverse/cmd/egress [no test files]
ok academy/proxies-forward-reverse/clientip 1.0s
ok academy/proxies-forward-reverse/fproxy 1.0s
ok academy/proxies-forward-reverse/rproxy 1.2s- Expected, not run: reproduce the spoofing with the naive function. A client that sends
X-Forwarded-For: 203.0.113.99gets that value back frombefore.ClientIP; theclientipversion returns the TCP peer. The testTestNaiveVersionIsSpoofableis exactly this experiment. - Expected, not run: start two tiny upstreams (
python3 -m http.server 8081and 8082), pointrproxyat them withUpstreams, stop one, and curl 20 times: every response is 200 because the dial error is retried on the other server and the dead one is ejected forEjectFor. - Expected, not run: make an upstream sleep longer than
ResponseHeaderTimeoutand observe504; stop all upstreams and observe502. - Expected, not run (NGINX):
nginx -t && nginx -s reloadwith the reference config;curl -sI -H 'X-Forwarded-For: 203.0.113.99' https://app.example.com/whoamithrough the proxy showsipequal to the real client address in the Laravel JSON whenTRUSTED_PROXIESincludes the proxy, and equal to the proxy address when it does not. - Expected, not run (CONNECT):
HTTPS_PROXY=http://svc:s3cret@127.0.0.1:3128 curl -v https://example.orgagainstEGRESS_ALLOW=example.org:443 EGRESS_CREDENTIALS=svc:s3cret go run ./cmd/egressshowsCONNECT example.org:443,HTTP/1.1 200 Connection Established, then a TLS handshake that the proxy cannot read; a destination not on the allow-list shows403, a missing password shows407.
Common misconceptions
| Belief | Reality |
|---|---|
| A proxy is a firewall | A firewall filters packets by rules; a proxy terminates a connection and opens another. Combine them; neither replaces the other |
| X-Forwarded-For is the client IP | It is a list; only entries added by proxies you operate are reliable; the leftmost is the client's own claim |
* in trusted proxies is fine because "we have a load balancer" | Only if the app cannot be reached any other way; otherwise any caller can forge the address |
| A reverse proxy only does load balancing | It also terminates TLS, caches, compresses, limits, filters, authenticates and normalises headers |
| Forward proxies cannot see HTTPS at all | They see host and port with CONNECT, and everything if TLS interception with a trusted CA is used |
| 504 means the application is down | It means the proxy stopped waiting; the application may be alive and still working |
proxy_read_timeout limits the whole request | It limits the gap between two reads from the upstream |
| Retrying on another server is always safe | Only for idempotent requests, or when no byte was delivered |
| HTTP/2 to the client means HTTP/2 to the app | The proxy usually speaks HTTP/1.1 upstream |
| Transparent proxy means no configuration or risk | It needs interception rules and, for HTTPS, a trusted CA; failures are hard to diagnose |
| PROXY protocol is just a header the server may use if present | The listener must be configured to require it from known proxies only |
| A WebSocket needs no special proxy config | Upgrade and Connection are hop-by-hop and must be passed explicitly, and idle timeouts apply |
Cheat sheet
| Topic | What to remember |
|---|---|
| Forward vs reverse | Forward speaks for clients (egress control); reverse speaks for servers (front door) |
| Gateway | RFC 9110: a gateway is a reverse proxy; a tunnel is a blind relay |
| CONNECT | Authority-form request, then 200 and blind byte copy; port-restrict it |
| L4 vs L7 | L4 moves bytes (passthrough, any protocol); L7 reads HTTP (routing, headers, caching) |
| TLS | Terminate for L7 features; passthrough to keep the key at the backend; re-encrypt inside shared networks |
| X-Forwarded-For | Comma list; read from the right through trusted hops; never the leftmost |
| Trusted proxies | Believe forwarding headers only from listed peers; Laravel trustProxies(at:, headers:) |
| PROXY protocol | One header at the start of the TCP stream; accept only from known proxies; v2 is binary |
| Hop-by-hop | Connection, Keep-Alive, Upgrade, TE, Trailer, Transfer-Encoding, Proxy-*: strip and reset per hop |
| 502 vs 504 | 502: invalid or no response; 504: no response in time |
| Timeouts | NGINX connect/send/read default 60 s; read and send are gaps, not totals |
| Buffering | Request buffering protects the app from slow clients; turn off for streaming |
| Keepalive upstream | HTTP/1.1, pooled connections, upstream idle timeout longer than the pool's |
| WebSocket | Pass Upgrade and Connection; lengthen the idle timeout; send pings |
| Retries | Idempotent and before any byte is delivered; never blindly on POST |
| Reload | Test the config, send HUP, old workers drain; restart drops connections |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What is the difference between a forward proxy and a reverse proxy, and who configures each? Must-know
Answer
Answer: A forward proxy is chosen by the client side (configuration, PAC, or interception) and speaks for clients toward many origins: egress control, caching, filtering. A reverse proxy is run by the server owner and reached through DNS; it speaks for servers toward many clients: TLS termination, routing, balancing. RFC 9110 calls the second a gateway.
2 — Why can a forward proxy not read an HTTPS URL path when the client uses CONNECT? Important
Answer
Answer: After the 200 response the proxy is a blind relay of TLS bytes (RFC 9110 section 9.3.6). It knows the host and port from the CONNECT target and sees volume and timing, but the path and headers are encrypted unless the proxy does TLS interception with a CA the client trusts.
3 — When is an L4 proxy the right choice over an L7 proxy? Must-know
Answer
Answer: For non-HTTP protocols, TLS passthrough where the backend must hold the key, extreme throughput, and as a first tier that spreads connections over several L7 proxies. The price is no routing by URL, no header changes and no per-request retries.
4 — An application behind NGINX logs the load balancer's address for every request. List the causes and the fix. Important
Answer
Answer: The application reads the TCP peer, which is the proxy. Fix: have the proxy set X-Forwarded-For (and Proto/Host), and configure the application to trust that proxy's address range (Laravel trustProxies(at: ...), NGINX set_real_ip_from), reading the address from the right through trusted hops. For L4 balancers use the PROXY protocol.
5 — Why is trusting * in trustProxies dangerous, and when is it acceptable? Must-know
Answer
Answer: Any caller who can reach the application directly can forge X-Forwarded-For, Proto and Host. It is acceptable only when the network guarantees every request arrives through your balancer (private subnet, security group allowing only the balancer).
6 — What does proxy_read_timeout 60s measure, and why can a request run for ten minutes without tripping it? Important
Answer
Answer: It measures the time between two successive read operations from the upstream, not the whole response. A server that sends data at least every 60 seconds keeps the connection alive indefinitely.
7 — Distinguish a 502 from a 504 and say which is safe to retry for a POST. Must-know
Answer
Answer: 502: the proxy got an invalid response or could not connect or the connection was reset. 504: the proxy gave up waiting. A POST should not be blindly retried after either, because the upstream may have performed the work; retry only with an idempotency key, or when the connection never opened.
8 — Why does a WebSocket fail through NGINX without extra configuration? Must-know
Answer
Answer: Upgrade and Connection are hop-by-hop headers and are removed. They must be set explicitly with proxy_set_header Upgrade $http_upgrade and proxy_set_header Connection "upgrade" (on older builds with HTTP/1.1 upstream), and the read timeout must be long enough for idle connections.
9 — What problem does the PROXY protocol solve and what is the main rule when enabling it? Important
Answer
Answer: It carries the original client and destination addresses across an L4 proxy that cannot add HTTP headers. The receiver must be configured to require it, only from trusted proxies; otherwise a client could send its own header and spoof an address.
10 — How do you deploy without dropping requests behind a proxy? Must-know
Answer
Answer: Fail readiness first so the proxy stops sending new requests, wait for the health check to eject the instance, drain in-flight requests, then stop it. For the proxy itself, test the config and reload (HUP) so old workers finish their requests.
Glossary
| Term | Definition |
|---|---|
| Forward proxy | Intermediary chosen by the client that forwards requests to origins and applies policy |
| Egress proxy | A forward proxy used to control outbound traffic from servers |
| Reverse proxy | Intermediary that acts as the origin for clients and forwards to backend servers; RFC 9110 calls it a gateway |
| Gateway | RFC 9110 term for a reverse proxy |
| Tunnel | A blind relay between two connections, created by CONNECT |
| Explicit proxy | A proxy the client is configured to use |
| Transparent proxy | A proxy the network steers traffic into without client configuration |
| PAC | Proxy auto-config: a JavaScript FindProxyForURL function that picks a proxy per URL |
| HTTP CONNECT | Method that asks a proxy to open a TCP tunnel to host:port |
| SOCKS5 | Protocol (RFC 1928) for relaying arbitrary TCP and UDP through a proxy |
| TLS termination | The proxy completes the TLS handshake and decrypts traffic |
| TLS passthrough | The proxy relays encrypted bytes; the backend holds the certificate |
| Re-encryption | Terminate TLS at the proxy, then open a new TLS connection to the upstream |
| L4 proxy | Proxy that relays TCP or UDP without parsing application protocols |
| L7 proxy | Proxy that parses and acts on application messages such as HTTP |
| Upstream | A backend server or pool a proxy forwards to (NGINX term) |
| X-Forwarded-For | De facto header listing client and proxy addresses, appended per hop |
| X-Forwarded-Proto | De facto header carrying the client-facing scheme |
| Forwarded | RFC 7239 standard header with for, by, host and proto |
| X-Real-IP | Single-address header set by one proxy, by convention |
| Trusted proxies | The list of peers whose forwarding headers an application believes |
| TrustProxies | Laravel middleware that applies trusted-proxy headers to the request |
| PROXY protocol | HAProxy protocol that prefixes a TCP connection with the original addresses |
| Hop-by-hop headers | Headers that apply to one connection and must not be forwarded |
| Via | Header recording the intermediaries a message passed through |
| 502 Bad Gateway | Proxy received an invalid response or could not reach the upstream |
| 504 Gateway Timeout | Proxy did not get a timely response from the upstream |
| proxy_read_timeout | NGINX timer for the gap between two reads from the upstream |
| Request buffering | Reading the whole request body at the proxy before contacting the upstream |
| Response buffering | Receiving the upstream response at the proxy before delivering it to the client |
| Keepalive upstream | Reusing idle connections from the proxy to the upstream |
| WebSocket proxying | Passing Upgrade and Connection so a connection can switch protocols through the proxy |
| Upgrade | Header requesting a protocol switch, answered by 101 |
| Health check | Probe or failure counting that decides whether an upstream receives traffic |
| Graceful reload | Applying new configuration while old workers finish their requests |
| WAF | Web application firewall: rules that block attack patterns in HTTP requests |
| Sidecar | A proxy deployed beside each service instance |
| API gateway | Edge reverse proxy with API features such as authentication and quotas |
| NGINX | Event-driven web server and reverse proxy |
| HAProxy | L4 and L7 proxy and load balancer |
| Envoy | L3/L4 and L7 proxy used as a mesh data plane and gateway |
| Traefik | Dynamic reverse proxy for container platforms |
| Caddy | Reverse proxy and web server with automatic HTTPS |
| Squid | Caching and filtering forward proxy |
| Cloudflare | Global reverse proxy and CDN service |
| ALB | AWS Application Load Balancer, a managed L7 balancer |
References
- RFC 9110, HTTP Semantics (intermediaries, CONNECT, Via, Connection, 502, 504): https://www.rfc-editor.org/rfc/rfc9110.html
- RFC 7239, Forwarded HTTP Extension: https://www.rfc-editor.org/rfc/rfc7239.html
- RFC 1928, SOCKS Protocol Version 5: https://www.rfc-editor.org/rfc/rfc1928.html
- NGINX, ngx_http_proxy_module: https://nginx.org/en/docs/http/ngx_http_proxy_module.html
- NGINX, ngx_http_upstream_module: https://nginx.org/en/docs/http/ngx_http_upstream_module.html
- NGINX, WebSocket proxying: https://nginx.org/en/docs/http/websocket.html
- NGINX, controlling NGINX (reload): https://nginx.org/en/docs/control.html
- NGINX documentation, reverse proxy guide: https://docs.nginx.com/nginx/admin-guide/web-server/reverse-proxy/
- HAProxy, PROXY protocol specification: https://www.haproxy.org/download/3.0/doc/proxy-protocol.txt
- HAProxy: https://www.haproxy.org/
- Envoy, what is Envoy: https://www.envoyproxy.io/docs/envoy/latest/intro/what_is_envoy
- Envoy, architecture overview: https://www.envoyproxy.io/docs/envoy/latest/intro/arch_overview/arch_overview
- Envoy, HTTP connection manager headers (X-Forwarded-For, use_remote_address): https://www.envoyproxy.io/docs/envoy/latest/configuration/http/http_conn_man/headers
- Laravel 13, Requests (trusting proxies, client IP): https://laravel.com/docs/13.x/requests
- Laravel 13, Octane (serving via Nginx): https://laravel.com/docs/13.x/octane
- Laravel 13, HTTP client (withOptions): https://laravel.com/docs/13.x/http-client
- Guzzle, request options (proxy): https://docs.guzzlephp.org/en/stable/request-options.html
- Go, net/http/httputil: https://pkg.go.dev/net/http/httputil
- MDN, Proxy auto-configuration (PAC) file: https://developer.mozilla.org/en-US/docs/Web/HTTP/Proxy_servers_and_tunneling/Proxy_Auto-Configuration_PAC_file
- MDN, CONNECT: https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods/CONNECT
- Squid FAQ, about Squid: https://wiki.squid-cache.org/SquidFaq/AboutSquid
- Squid configuration reference: http://www.squid-cache.org/Doc/config/
- Caddy, reverse_proxy: https://caddyserver.com/docs/caddyfile/directives/reverse_proxy
- Traefik documentation: https://doc.traefik.io/traefik/
- Cloudflare, HTTP headers (CF-Connecting-IP): https://developers.cloudflare.com/fundamentals/reference/http-headers/
- AWS, Application Load Balancer HTTP headers (X-Forwarded-For): https://docs.aws.amazon.com/elasticloadbalancing/latest/application/x-forwarded-headers.html
- AWS, Network Load Balancers: https://docs.aws.amazon.com/elasticloadbalancing/latest/network/network-load-balancers.html