TExcelTAD
Home › Linux Server Administration › Nginx as a Reverse Proxy

Nginx as a Reverse Proxy

Applications rarely face the internet directly. A reverse proxy in front of them terminates TLS, serves static files, compresses responses, enforces limits, spreads load over several app processes, and gives you one place for logs and headers. Nginx is the most common choice. This lesson covers what a server admin needs to put an app behind it; the deep version (caching, rate limiting, HAProxy and Traefik) is the planned Web Servers in Depth course, and Load Balancing has the theory.

What the backend sees

Behind a proxy, every request reaches the app from the proxy's address, over plain HTTP. Unless the proxy passes the original details in headers, the app logs 127.0.0.1 for every visitor and builds http:// links on an HTTPS site. The session runs a tiny backend that prints the headers it receives:

bash · try it yourself
cat > echo_app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        body = f"backend :{sys.argv[1]} path={self.path}\n"
        for k in ("Host", "X-Real-IP", "X-Forwarded-For", "X-Forwarded-Proto"):
            body += f"  {k}: {self.headers.get(k)}\n"
        self.send_response(200); self.end_headers(); self.wfile.write(body.encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 echo_app.py 9001 &
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log stderr;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    location /bare/ {
      proxy_pass http://127.0.0.1:9001/;              # no extra headers
    }
    location /api/ {
      proxy_pass http://127.0.0.1:9001;               # no URI part: path passed unchanged
      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;
    }
  }
}
EOF
nginx -t -p "$PWD" -c nginx.conf -e stderr 2>&1 | tail -1
for i in $(seq 50); do curl -s 127.0.0.1:9001/ > /dev/null && break; sleep 0.1; done
nginx -p "$PWD" -c nginx.conf -e stderr
echo "=== /bare/users"
curl -s -H "Host: shop.example.test" http://127.0.0.1:8080/bare/users
echo "=== /api/users (a client that already came through another proxy)"
curl -s -H "Host: shop.example.test" -H "X-Forwarded-For: 203.0.113.9" http://127.0.0.1:8080/api/users
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1
nginx: configuration file /home/learner/nginx.conf test is successful
=== /bare/users
backend :9001 path=/users
  Host: 127.0.0.1:9001
  X-Real-IP: None
  X-Forwarded-For: None
  X-Forwarded-Proto: None
=== /api/users (a client that already came through another proxy)
backend :9001 path=/api/users
  Host: shop.example.test
  X-Real-IP: 127.0.0.1
  X-Forwarded-For: 203.0.113.9, 127.0.0.1
  X-Forwarded-Proto: http

Two things to see:

  • Headers. Without proxy_set_header, Nginx sends Host: 127.0.0.1:9001 (the upstream's address) and nothing about the client. With them, the app sees the real host name, the client address, the chain of proxies in X-Forwarded-For and the original scheme. The app (or its framework: Django's SECURE_PROXY_SSL_HEADER, Express's trust proxy, Rails' trusted_proxies) must be told to trust these headers only from the proxy, otherwise any client can forge X-Forwarded-For.
  • The path. proxy_pass http://127.0.0.1:9001/; (with a URI part, the trailing /) replaces the matched location prefix: /bare/users becomes /users. proxy_pass http://127.0.0.1:9001; (no URI) passes the path unchanged: /api/users stays /api/users. That single slash causes more broken proxies than anything else.

Several backends: upstream blocks

An upstream block names a group of backends. Nginx balances round-robin by default (least_conn and ip_hash are alternatives), and when a backend refuses connections it tries the next one (proxy_next_upstream error timeout is the default) and marks the failed one as down for fail_timeout (10 s):

bash · try it yourself
cat > echo_app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"served by :{sys.argv[1]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 echo_app.py 9001 & P1=$!
python3 echo_app.py 9002 & P2=$!
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  upstream app {
    server 127.0.0.1:9001 max_fails=1 fail_timeout=10s;
    server 127.0.0.1:9002 max_fails=1 fail_timeout=10s;
    keepalive 16;
  }
  server {
    listen 127.0.0.1:8080;
    location / {
      proxy_pass http://app;
      proxy_http_version 1.1;
      proxy_set_header Connection "";
      proxy_connect_timeout 2s;
      proxy_read_timeout 30s;
    }
  }
}
EOF
for p in 9001 9002; do for i in $(seq 50); do curl -s 127.0.0.1:$p/ > /dev/null && break; sleep 0.1; done; done
nginx -p "$PWD" -c nginx.conf -e stderr
echo "--- both backends up:"
for i in 1 2 3 4; do curl -s localhost:8080/; done
kill $P1; sleep 0.3
echo "--- backend 9001 stopped:"
for i in 1 2 3 4; do curl -s -o /dev/null -w "%{http_code} " localhost:8080/; done; echo
grep -c 'connect() failed' error.log
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill $P2
--- both backends up:
served by :9001
served by :9002
served by :9001
served by :9002
--- backend 9001 stopped:
200 200 200 200
1

No request failed when a backend died: the one request that hit the dead backend was retried on the other, and Nginx then stopped sending traffic there for fail_timeout. Retrying is only safe for requests that can be repeated; by default Nginx doesn't retry a POST once it has been sent to a backend (non-idempotent requests), which is the behaviour you want.

keepalive 16 with proxy_http_version 1.1 and an empty Connection header reuses backend connections instead of opening one per request, which matters at high request rates.

The production checklist

nginx
server {
    listen 443 ssl;
    http2 on;                              # nginx >= 1.25.1; on 1.24 (Ubuntu 24.04): listen 443 ssl http2;
    server_name shop.example.com;
    # ssl_certificate ... (see "Terminating TLS")

    client_max_body_size 20m;              # uploads larger than the 1m default
    location /static/ { root /srv/shop; expires 7d; access_log off; }

    location /ws/ {                        # WebSockets need the upgrade headers
        proxy_pass http://app;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_read_timeout 1h;
    }
    location / {
        proxy_pass http://app;
        include /etc/nginx/proxy_params;   # Debian/Ubuntu's Host, X-Real-IP, X-Forwarded-* lines
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

On Debian/Ubuntu, sites live in /etc/nginx/sites-available/ and are enabled with a symlink in sites-enabled/; other distributions use /etc/nginx/conf.d/*.conf. Before every reload: sudo nginx -t && sudo systemctl reload nginx. A reload starts new workers with the new config and lets old ones finish their requests, so it doesn't drop connections; nginx -T prints the full effective configuration with all includes.

Test yourself

location /app/ { proxy_pass http://127.0.0.1:9000/; } receives /app/login. What path does the backend get?

  1. /app/login
  2. /login
  3. /app/
  4. /

Why must the app trust X-Forwarded-For only from the proxy?

  1. Performance
  2. Any client can send that header; trusting it from everyone lets attackers fake their IP address in logs and rate limits
  3. It is encrypted
  4. Nginx removes it otherwise

One of two upstream servers is stopped. What do clients of the session's configuration see?

  1. Every second request fails with 502
  2. Requests succeed: Nginx retries on the other server and marks the dead one as failed
  3. All requests fail
  4. Nginx stops