Appendix C — nginx and Caddy Side by Side
You will meet both servers in the wild. Caddy’s config reads like a list of intentions. nginx’s reads like a list of instructions. Both sit in front of your app on a small production VPS and both do the job well. This page lays each case side by side, so when you open someone else’s config at 2 a.m., you can read it in either language.
For the ideas behind these lines, read Chapter 8, reverse proxies and Chapter 9, HTTPS.
The mapping at a glance
Section titled “The mapping at a glance”| Job | Caddyfile | nginx |
|---|---|---|
| Serve files | file_server |
root + try_files |
| Proxy to an app | reverse_proxy |
proxy_pass |
| Set a header | header |
add_header, proxy_set_header |
| Redirect | redir |
return 301 |
| Path prefix to another upstream | handle /api/* |
location /api/ |
| Upload size limit | request_body |
client_max_body_size |
| Basic auth | basic_auth |
auth_basic |
| Check the config | caddy validate |
nginx -t |
Caddy gets certificates for named sites on its own. nginx leaves that job to certbot or to files you manage yourself.
Static site
Section titled “Static site”pipeslab.in { root * /var/www/pipeslab file_server}server { listen 80; server_name pipeslab.in; root /var/www/pipeslab;
location / { try_files $uri $uri/ =404; }}Caddy issues the certificate once DNS points at the box. The nginx block serves plain HTTP, so add TLS the way Chapter 9 describes before you call it done. try_files says: look for the file, then the folder, then give up.
Reverse proxy with the right headers
Section titled “Reverse proxy with the right headers”The app listens on 127.0.0.1:3000, so it never faces the street. The proxy has to tell the app who the visitor really was.
app.pipeslab.in { reverse_proxy 127.0.0.1:3000}Caddy sets X-Forwarded-For, X-Forwarded-Proto and X-Forwarded-Host by default. You rarely add more.
server { listen 80; server_name app.pipeslab.in;
location / { proxy_pass http://127.0.0.1:3000; 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; }}WebSockets
Section titled “WebSockets”Caddy’s reverse_proxy handles WebSocket upgrades on its own, so the block you already have does the job. nginx is more explicit. It talks HTTP/1.0 to upstreams unless you say otherwise, and an upgrade needs HTTP/1.1 plus two headers.
app.pipeslab.in { reverse_proxy 127.0.0.1:3000}location /ws/ { proxy_pass http://127.0.0.1:3000; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; proxy_read_timeout 3600s;}The literal Connection "upgrade" suits a location that only carries sockets. If one server block mixes socket and plain HTTP traffic, the usual move is a map $http_upgrade $connection_upgrade block at the top of the file. The long proxy_read_timeout stops idle sockets from being cut at the 60-second default.
Redirects: www to apex, HTTP to HTTPS
Section titled “Redirects: www to apex, HTTP to HTTPS”Caddy gets certificates and redirects HTTP to HTTPS for every named site, so the www case is one line.
www.pipeslab.in { redir https://pipeslab.in{uri} permanent}server { listen 80; listen 443 ssl; server_name www.pipeslab.in; ssl_certificate /etc/letsencrypt/live/pipeslab.in/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/pipeslab.in/privkey.pem; return 301 https://pipeslab.in$request_uri;}
server { listen 80; server_name pipeslab.in; return 301 https://$host$request_uri;}The 443 ssl line on www needs a certificate that names www, so issue one with both names (Chapter 9). The apex’s HTTPS block lives in your site block, not here. Use 301 only once you are sure of the canonical host. Browsers remember permanent redirects for a long time, so 302 is the safer first try.
Several subdomains on one box
Section titled “Several subdomains on one box”One box, one IP, many names. The Host header decides which site answers. Caddy writes one block per name. nginx writes one server block per name and matches it on server_name.
app.pipeslab.in { reverse_proxy 127.0.0.1:3000}
api.pipeslab.in { reverse_proxy 127.0.0.1:4000}
staging.pipeslab.in { root * /var/www/staging file_server}server { listen 80; server_name app.pipeslab.in; location / { proxy_pass http://127.0.0.1:3000; proxy_set_header Host $host; }}
server { listen 80; server_name api.pipeslab.in; location / { proxy_pass http://127.0.0.1:4000; proxy_set_header Host $host; }}
server { listen 80 default_server; server_name _; return 444;}The last block is a catch-all. Without it, a request for a name you never configured lands on whichever site sorts first in the file. 444 is nginx’s way of closing the connection with no reply. Caddy answers only the names it knows, so it needs no catch-all for this case, though a small :80 block that aborts unknown hosts is a common hedge. Check the current Caddy docs for its exact form.
Path routing: /api to another upstream
Section titled “Path routing: /api to another upstream”Caddy runs handle blocks in order, and the first match wins. A bare handle with no matcher is the fallback.
pipeslab.in { handle /api/* { reverse_proxy 127.0.0.1:4000 }
handle { reverse_proxy 127.0.0.1:3000 }}handle keeps the prefix, so the upstream sees /api/users. If the upstream expects /users, use handle_path /api/* instead, which strips the prefix for you.
server { listen 80; server_name pipeslab.in;
location /api/ { proxy_pass http://127.0.0.1:4000; }
location / { proxy_pass http://127.0.0.1:3000; }}Leave out the forwarded headers above, as in the earlier block, and add them back in a real config. To strip the prefix in nginx, the only change is the slash after the port:
location /api/ { proxy_pass http://127.0.0.1:4000/;}Upload size limits
Section titled “Upload size limits”Uploads are where the defaults differ most. nginx caps request bodies at 1 MB out of the box, so a 2 MB photo gets a bare 413 before your app ever sees it. Caddy sets no cap, which is generous right up until someone uploads a 4 GB file onto your VPS disk.
pipeslab.in { request_body { max_size 25MB } reverse_proxy 127.0.0.1:3000}server { server_name pipeslab.in; client_max_body_size 25m;
location / { proxy_pass http://127.0.0.1:3000; }}Set the limit where it applies: the whole site block or server block, or one location when only a single route takes files. Then make your frontend’s “file too big” message quote the same number.
Timeouts
Section titled “Timeouts”A timeout decides how long a slow upstream can hold a connection before the proxy gives up with a 504. nginx’s read and send timeouts default to 60 seconds. Caddy keeps its knobs under the transport block.
location / { proxy_pass http://127.0.0.1:3000; proxy_connect_timeout 5s; # wait this long for the TCP connect proxy_read_timeout 60s; # wait this long between response bytes proxy_send_timeout 60s; # wait this long between request writes}reverse_proxy 127.0.0.1:3000 { transport http { dial_timeout 5s response_header_timeout 60s }}The Caddy key names have shifted between versions, so check the reference for yours before you rely on them. Raise the timeout for the one slow report route, not for the whole site. A long timeout everywhere only means slow failures everywhere. When you see a 504 in the logs, the app is usually the slow part, not the timeout.
Basic auth for a staging site
Section titled “Basic auth for a staging site”Put staging behind a password so search engines and strangers stay out. nginx takes an htpasswd file, which you can make with htpasswd from the apache2-utils package. Caddy takes a bcrypt hash, which caddy hash-password prints for you.
server { server_name staging.pipeslab.in;
auth_basic "Staging"; auth_basic_user_file /etc/nginx/.htpasswd;
location / { proxy_pass http://127.0.0.1:3100; }}staging.pipeslab.in { basic_auth { ops <bcrypt hash from caddy hash-password> } reverse_proxy 127.0.0.1:3100}Caddy spells the directive basic_auth in v2, and recent releases also accept basicauth. Check your version if one of them errors.
Security headers
Section titled “Security headers”These headers ask the browser to be stricter. Set them once, at the server level, and mind the nginx gotcha below.
server_tokens off;add_header Strict-Transport-Security "max-age=31536000" always;add_header X-Content-Type-Options "nosniff" always;add_header X-Frame-Options "DENY" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;header { Strict-Transport-Security "max-age=31536000" X-Content-Type-Options "nosniff" X-Frame-Options "DENY" Referrer-Policy "strict-origin-when-cross-origin" -Server}Two traps. First, nginx’s add_header inside a location replaces every add_header from the server block for that location, so one location with its own header line quietly drops your security headers. Second, adding includeSubDomains to HSTS locks out any subdomain still answering only on HTTP, so add it only after every subdomain speaks HTTPS. The always flag makes nginx send the headers on error pages too, which you want.
Rate limiting
Section titled “Rate limiting”nginx has rate limiting built in. You define a zone once in the http block, then attach it to the routes that need it. Caddy’s core has no rate limiter, so you add a third-party module, usually compiled in with xcaddy. The Caddy syntax below follows one popular module from memory. Check its README before you copy it.
# http block, outside any serverlimit_req_zone $binary_remote_addr zone=login:10m rate=5r/s;
server { location = /login { limit_req zone=login burst=10 nodelay; limit_req_status 429; proxy_pass http://127.0.0.1:3000; }}pipeslab.in { rate_limit { zone login { key {remote_host} events 5 window 1s } } reverse_proxy 127.0.0.1:3000}burst=10 lets a short spike queue up, and nodelay serves that spike at once instead of spacing it out. Without limit_req_status 429, nginx answers rejected requests with a 503, which makes the rejection look like an outage. Apply the limit to the login, signup and password-reset routes, not the whole site. A browser loading a page with forty assets would trip a site-wide limit on its own. Rate limits exist for the doorknob-rattlers, not for your users.
Real client IP behind Cloudflare
Section titled “Real client IP behind Cloudflare”When Cloudflare sits in front of your server, the TCP connection arrives from a Cloudflare address, not from the visitor. Your logs then show the same doorman for everyone. Cloudflare copies the visitor’s address into the CF-Connecting-IP header, and you tell your proxy to believe that header, but only when it comes from Cloudflare’s own ranges. Trust it from anywhere and any client can write whatever address it likes.
# http block: one set_real_ip_from line per range listed at cloudflare.com/ipsset_real_ip_from 203.0.113.0/24; # example range only, not the real listreal_ip_header CF-Connecting-IP;{ servers { trusted_proxies static 203.0.113.0/24 client_ip_headers CF-Connecting-IP }}Recent Caddy versions have the client_ip_headers option. Older ones read only X-Forwarded-For from trusted proxies, so check the docs for your version. The Cloudflare ranges change now and then, so put the refresh on a schedule rather than trusting a list you copied years ago.
The nginx location-matching order
Section titled “The nginx location-matching order”When a request arrives, nginx does not pick the first location in the file. It runs a fixed sequence, and the order is the thing most people get wrong.
| Step | Form | What happens |
|---|---|---|
| 1 | location = /path |
An exact match wins at once. The search stops. |
| 2 | location ^~ /path |
The longest matching prefix is remembered. If it has ^~, the search stops here and regexes are skipped. |
| 3 | location ~ pattern or ~* |
Regexes are tried in file order. The first match wins. ~* ignores case. |
| 4 | location /path |
If no regex matched, the longest remembered prefix from step 2 is used. |
So a regex beats a plain prefix, unless you stop it with ^~. Given location /static/ and location ~* \.css$, a request for /static/site.css hits the regex, not the prefix. Put ^~ on the prefix when you want the directory to win, and use = for the one exact URL you care about.
Caddy has no equivalent puzzle. Its handle blocks are mutually exclusive, the first one that matches wins, and the directives inside them run in a fixed built-in order. Read a Caddyfile top to bottom and you see the order it runs in.
Test, then reload
Section titled “Test, then reload”Never reload a web server you have not just checked. Both tools can validate the file without touching the running server, and a reload swaps in the new config without dropping open connections, unlike a restart.
# nginx: check first; reload runs only if the check passessudo nginx -t && sudo systemctl reload nginx# Caddy: validate, then reload through the local admin APIcaddy validate --config /etc/caddy/Caddyfilesudo caddy reload --config /etc/caddy/CaddyfileThe && is the important part. When nginx -t fails, the reload never runs, and the old config keeps serving traffic. If your Caddy runs under systemd, sudo systemctl reload caddy does the same job. Errors from a failed check name the file and the line, so read the first error and ignore the cascade below it. For the messages you will meet when a check or a live request goes wrong, see Appendix E.
Book 2 of a series. Book 1: The Glue.