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

Caddy as a Reverse Proxy

Caddy is a web server written in Go whose headline feature is automatic HTTPS: give it a domain name and it obtains, installs and renews a certificate from Let's Encrypt (or ZeroSSL) on its own. Its configuration file, the Caddyfile, is short, and its defaults are modern (HTTP/2 and HTTP/3, sensible TLS, the X-Forwarded-* headers set for you). For a single server running a few apps, it is often the least work.

A Caddyfile

text
shop.example.com {
    encode zstd gzip
    handle_path /static/* {
        root * /srv/shop/static
        file_server
    }
    reverse_proxy 127.0.0.1:9001 127.0.0.1:9002 {
        lb_policy least_conn
        health_uri /health
        health_interval 10s
    }
}

grafana.example.com {
    reverse_proxy 127.0.0.1:3000
}

That is a complete production config: two HTTPS sites with certificates, HTTP→HTTPS redirects, compression, static files and a load-balanced, health-checked app. Compare it with the equivalent Nginx configuration plus certbot.

Caddyfile Meaning
shop.example.com { … } a site block; a real domain name turns on automatic HTTPS for it
:8080 { … } a site on a port with no name: plain HTTP
reverse_proxy a b proxy to one or more upstreams; X-Forwarded-For, -Proto and -Host are added automatically
handle_path /static/* handle a path prefix and strip it (handle keeps it)
header_up / header_down change request headers to the upstream / response headers to the client
{ … } at the top global options (email for ACME, admin endpoint, auto_https off)

Running it in the session

The sandbox can't get public certificates, so the session uses plain HTTP on port 8080 (auto_https off). Everything else is the real Caddy 2.11:

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} xff={self.headers.get('X-Forwarded-For')} proto={self.headers.get('X-Forwarded-Proto')}\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 &
python3 echo_app.py 9002 &
cat > Caddyfile <<'EOF'
{
    auto_https off
}
:8080 {
    handle_path /api/* {
        reverse_proxy 127.0.0.1:9001 127.0.0.1:9002 {
            lb_policy round_robin
        }
    }
    respond "front page"
}
EOF
caddy fmt --overwrite Caddyfile
caddy validate --config Caddyfile 2>&1 | tail -1
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
caddy start --config Caddyfile > caddy.log 2>&1 && echo "caddy started"
for i in $(seq 50); do curl -s localhost:8080/ > /dev/null && break; sleep 0.1; done
curl -s 127.0.0.1:8080/; echo
for i in 1 2 3; do curl -s 127.0.0.1:8080/api/orders; done
curl -sI 127.0.0.1:8080/api/orders | grep -i '^via' | tr -d '\r'
caddy stop > /dev/null 2>&1 && echo "caddy stopped"
kill %1 %2
Valid configuration
caddy started
front page
backend :9002 path=/orders xff=127.0.0.1 proto=http
backend :9001 path=/orders xff=127.0.0.1 proto=http
backend :9002 path=/orders xff=127.0.0.1 proto=http
Via: 1.0 Caddy
caddy stopped

caddy fmt --overwrite normalises the file's indentation (Caddy warns about unformatted files). caddy validate loads the config fully without serving it: run it before every reload, like nginx -t. handle_path /api/* stripped /api before proxying, and Caddy set X-Forwarded-For and X-Forwarded-Proto without being asked; it also adds a Via header to responses.

The Caddyfile is a front end to JSON

Caddy's real configuration format is JSON; the Caddyfile is converted ("adapted") to it. caddy adapt shows the result, which helps when a directive doesn't behave as expected:

bash · try it yourself
cat > Caddyfile <<'EOF'
:8080 {
	reverse_proxy 127.0.0.1:9001
}
EOF
caddy adapt --config Caddyfile 2>/dev/null | jq -c '.apps.http.servers.srv0 | {listen, handler: .routes[0].handle[0].handler, upstreams: .routes[0].handle[0].upstreams}'
{"listen":[":8080"],"handler":"reverse_proxy","upstreams":[{"dial":"127.0.0.1:9001"}]}

A running Caddy also exposes this JSON on its admin API (localhost:2019 by default): curl localhost:2019/config/ returns the live config, and caddy reload pushes a new one there without dropping connections. Keep the admin endpoint on localhost (the default), or turn it off with admin off if nothing uses it.

Caddy on a server

bash
# Sample session (Ubuntu, Caddy's official apt repository)
$ sudo apt install caddy
$ systemctl status caddy | head -3
● caddy.service - Caddy
     Loaded: loaded (/usr/lib/systemd/system/caddy.service; enabled; preset: enabled)
     Active: active (running) since Thu 2026-01-15 10:00:02 UTC; 2min ago
$ sudoedit /etc/caddy/Caddyfile
$ caddy validate --config /etc/caddy/Caddyfile && sudo systemctl reload caddy
$ journalctl -u caddy --since "5 min ago" -o cat | grep -m1 'certificate obtained'
{"level":"info","ts":1768471325.12,"logger":"tls.obtain","msg":"certificate obtained successfully","identifier":"shop.example.com","issuer":"acme-v02.api.letsencrypt.org-directory"}

The packaged service runs Caddy as the caddy user, with CAP_NET_BIND_SERVICE so it can bind ports 80 and 443 without root, and stores certificates under /var/lib/caddy/.local/share/caddy. Back that directory up or rebuild it consciously: a server that loses it requests new certificates at start, and rebuilding many servers at once can run into the CA's rate limits. Automatic HTTPS needs ports 80 and/or 443 reachable from the internet and DNS pointing at the server; ACME & Let's Encrypt explains why.

Nginx or Caddy?

Nginx Caddy
HTTPS certificates external (certbot, acme.sh, cert-manager) built in, automatic
config powerful, verbose, many modules short, opinionated defaults; JSON API for automation
ecosystem and know-how everywhere; most examples on the internet smaller, growing
performance the reference for high traffic more than enough for most sites
dynamic config reload; dynamic upstreams in NGINX Plus or with Lua admin API, on-demand TLS for many domains

Both are fine choices. Pick one per environment and know its validate-then-reload routine by heart.

Test yourself

What turns on automatic HTTPS for a site in a Caddyfile?

  1. A tls on directive
  2. Using a real domain name as the site address (with ports 80/443 reachable and DNS pointing to the server)
  3. Port 8080
  4. The admin API

What is the difference between handle and handle_path in Caddy?

  1. None
  2. handle_path strips the matched path prefix before the inner directives run; handle keeps it
  3. handle_path only serves files
  4. handle is deprecated

Why back up Caddy's data directory on a production server?

  1. It holds the logs
  2. It holds the obtained certificates and ACME account; losing it forces new issuance, which can hit CA rate limits
  3. It holds the Caddyfile
  4. It isn't needed