TExcelTAD

Web Server Exercises

Each exercise starts with a broken configuration and a session that shows the problem. Run the starter, read the output, fix the configuration in the editor until you get the expected output, then compare with the solution. Every starter is a complete session: the servers are started and tested with curl exactly as in the lessons.

Exercise 1: The API that serves HTML

Topics: Location Matching Order, root, alias & try_files, Nginx as a Reverse Proxy

A single-page app and its API share one server block. Two bugs: API calls that end in .json get the app shell instead of reaching the API, and the API receives /api/... although it expects paths without the prefix.

bash · try it yourself
mkdir -p www && echo "<app shell>" > www/index.html
cat > api.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"api: {self.path}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 api.py &
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  server {
    listen 127.0.0.1:8080;
    root www;
    location / { try_files $uri /index.html; }
    location ~* \.(json|js|css)$ { try_files $uri /index.html; expires 1h; }
    location /api/ { proxy_pass http://127.0.0.1:9000; }
  }
}
EOF
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
nginx -p "$PWD" -c nginx.conf -e stderr
for u in /orders /api/links /api/links/7.json; do printf '%-20s -> %s\n' "$u" "$(curl -s 127.0.0.1:8080$u)"; done
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null; kill %1
/orders              -> <app shell>
/api/links           -> api: /api/links
/api/links/7.json    -> <app shell>

Expected output:

text
/orders              -> <app shell>
/api/links           -> api: /links
/api/links/7.json    -> api: /links/7.json
Show solution
nginx
location / { try_files $uri /index.html; }
location ~* \.(json|js|css)$ { try_files $uri /index.html; expires 1h; }
location ^~ /api/ { proxy_pass http://127.0.0.1:9000/; }   # ^~ stops the regex search; the URI part "/" strips /api/

The regex location beat the longer /api/ prefix (regexes are checked after the longest prefix is found), so ^~ is needed. proxy_pass with a URI part (/) replaces the matched prefix. (A static-asset regex that falls back to index.html is itself a bad idea: missing assets should be 404s.)

Exercise 2: The rate limit that never fires

Topics: Rate & Connection Limits, How Nginx Processes a Request

The login endpoint should allow a burst of 2 and then answer 429. The limit seems to do nothing.

bash · try it yourself
cat > nginx.conf <<'EOF'
pid nginx.pid;
error_log error.log;
events {}
http {
  access_log off;
  limit_req_zone $binary_remote_addr zone=login:1m rate=1r/m;
  server {
    listen 127.0.0.1:8080;
    location = /login {
      limit_req zone=login burst=2 nodelay;
      return 200 "login form\n";
    }
  }
}
EOF
nginx -p "$PWD" -c nginx.conf -e stderr
echo "$(for i in 1 2 3 4 5; do curl -s -o /dev/null -w '%{http_code} ' 127.0.0.1:8080/login; done)"
nginx -p "$PWD" -c nginx.conf -e stderr -s quit 2>/dev/null
200 200 200 200 200

Expected output:

text
200 200 200 429 429
Show solution
nginx
limit_req_zone $binary_remote_addr zone=login:1m rate=1r/m;
limit_req_status 429;                                  # the default rejection status is 503
server {
    listen 127.0.0.1:8080;
    location = /login {
        limit_req zone=login burst=2 nodelay;
        proxy_pass http://127.0.0.1:9000;              # or: root + a file; anything but `return`
    }
}

return runs in the rewrite phase, before limit_req gets a chance, so the location was never limited. With real content (a file or proxy_pass), the first request plus two burst slots pass, then 429. To test without a backend, serve a file: root www; and try_files /login.html =404;.

Exercise 3: HAProxy keeps sending traffic to a dead server

Topics: Health Checks & Balancing, The Runtime API

web2 answers its health endpoint with 503, yet it stays UP and every second request fails.

bash · try it yourself
cat > app.py <<'EOF'
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        sick = sys.argv[2] == "web2"
        code = 503 if sick else 200
        self.send_response(code); self.end_headers(); self.wfile.write(f"{sys.argv[2]} {code}\n".encode())
    def log_message(self, *a): pass
ThreadingHTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 web1 & python3 app.py 9002 web2 &
cat > haproxy.cfg <<'EOF'
global
  pidfile haproxy.pid
  stats socket "${HOME}/admin.sock" mode 600 level admin
defaults
  mode http
  timeout connect 1s
  timeout client 5s
  timeout server 5s
frontend fe
  bind 127.0.0.1:8080
  default_backend be_app
backend be_app
  option httpchk GET /health
  http-check expect status 200
  default-server inter 300ms fall 2 rise 2
  server web1 127.0.0.1:9001
  server web2 127.0.0.1:9002
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
haproxy -c -f haproxy.cfg && haproxy -D -f haproxy.cfg
sleep 1.5
hap() { python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.connect("admin.sock"); s.sendall((sys.argv[1]+"\n").encode()); r=s.makefile().read().strip(); r and print(r)' "$1"; }
hap "show stat" | awk -F, '$1=="be_app" && $2 ~ /^web/ {print $2, $18}'
for i in 1 2 3 4; do curl -s 127.0.0.1:8080/; done
kill $(cat haproxy.pid) %1 %2
Configuration file is valid
web1 no check
web2 no check
web1 200
web2 503
web1 200
web2 503

Expected output:

text
Configuration file is valid
web1 UP
web2 DOWN
web1 200
web1 200
web1 200
web1 200
Show solution
text
backend be_app
  option httpchk GET /health
  http-check expect status 200
  default-server check inter 300ms fall 2 rise 2     # "check" turns the probes on
  server web1 127.0.0.1:9001
  server web2 127.0.0.1:9002

option httpchk only says how to check; without check on the server lines (or in default-server) no checks run, and HAProxy reports such servers as no check and keeps sending traffic.

Exercise 4: Caddy and the API prefix

Topics: The Caddyfile in Depth

/api/admin/* must be refused with 403, and the API expects paths without /api. The app currently sees the prefix. Also make the admin rule independent of Caddy's built-in directive order.

bash · try it yourself
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class H(BaseHTTPRequestHandler):
    def do_GET(self):
        self.send_response(200); self.end_headers(); self.wfile.write(f"app saw {self.path}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", 9000), H).serve_forever()
EOF
python3 app.py &
cat > Caddyfile <<'EOF'
{
	auto_https off
}
:8080 {
	reverse_proxy /api/* 127.0.0.1:9000
	respond /api/admin/* "forbidden" 403
}
EOF
caddy fmt --overwrite Caddyfile
for i in $(seq 50); do curl -s 127.0.0.1:9000/ > /dev/null && break; sleep 0.1; done
caddy start --config Caddyfile > caddy.log 2>&1
for u in /api/links /api/admin/users; do printf '%-18s -> %s\n' "$u" "$(curl -s -w ' [%{http_code}]' 127.0.0.1:8080$u | tr -d '\n')"; done
caddy stop > /dev/null 2>&1; kill %1
/api/links         -> app saw /api/links [200]
/api/admin/users   -> forbidden [403]

Expected output:

text
/api/links         -> app saw /links [200]
/api/admin/users   -> forbidden [403]
Show solution
text
:8080 {
	handle /api/admin/* {
		respond "forbidden" 403
	}
	handle_path /api/* {
		reverse_proxy 127.0.0.1:9000
	}
}

In the starter, respond happens to come before reverse_proxy in Caddy's directive order, so admin requests were already refused; that is easy to break without noticing (swap in a directive that sorts earlier, and admin requests reach the app). mutually exclusive handle blocks make the intent explicit, and handle_path strips /api.

Exercise 5: Traefik's catch-all swallows the API

Topics: Traefik: Entry Points, Routers & Services

A catch-all router for all customer domains was added, and now API requests go to the website.

bash · try it yourself
cat > 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"{sys.argv[2]}\n".encode())
    def log_message(self, *a): pass
HTTPServer(("127.0.0.1", int(sys.argv[1])), H).serve_forever()
EOF
python3 app.py 9001 website & python3 app.py 9002 api &
cat > traefik.yml <<'EOF'
global: {checkNewVersion: false, sendAnonymousUsage: false}
entryPoints:
  web: {address: "127.0.0.1:8080"}
  traefik: {address: "127.0.0.1:8081"}
api: {insecure: true}
providers:
  file: {filename: dynamic.yml, watch: false}
log: {level: ERROR}
EOF
cat > dynamic.yml <<'EOF'
http:
  routers:
    customer-sites:
      rule: "HostRegexp(`^[a-z0-9-]+\\.shops\\.example

  
    
    
    Web Server Exercises - Web Servers in Depth: Nginx, HAProxy, Caddy & Traefik · ExcelTAD
    
    
    
    
    
    
    
    
    
    
    
    
    
    
  
  
    )"
      service: website
    api:
      rule: "PathPrefix(`/api`)"
      service: api
  services:
    website: {loadBalancer: {servers: [{url: "http://127.0.0.1:9001"}]}}
    api:     {loadBalancer: {servers: [{url: "http://127.0.0.1:9002"}]}}
EOF
traefik --configFile=traefik.yml > traefik.log 2>&1 &
for i in $(seq 100); do curl -sf 127.0.0.1:8081/api/http/routers/api@file > /dev/null && break; sleep 0.1; done
for u in / /api/orders; do printf '%-12s -> %s\n' "$u" "$(curl -s -H 'Host: acme.shops.example' 127.0.0.1:8080$u)"; done
kill %3 %1 %2
/            -> website
/api/orders  -> website

Expected output:

text
/            -> website
/api/orders  -> api
Show solution
yaml
    api:
      rule: "PathPrefix(`/api`)"
      service: api
      priority: 100          # higher than the catch-all's default (its rule length)

The default priority is the rule's length: the long HostRegexp rule outranked the short PathPrefix rule. Set explicit priorities whenever a broad rule is long.

Test yourself

In Exercise 2, why did limit_req never reject anything?

  1. The rate was too high
  2. return runs in the rewrite phase, before the limit is applied
  3. limit_req needs a zone per location
  4. The burst was too large

In Exercise 3, what does option httpchk alone do?

  1. Enables checks for all servers
  2. Only defines how checks are made; servers need check to be probed
  3. Marks servers DOWN
  4. Nothing at all