Menu

Tutorials

How to Configure Caddy as a Production Reverse Proxy with Automatic HTTPS

Table of contents (7 sections)

Running a web application on a virtual private server still requires a reliable front door. Your Node.js, Go, Python, or Rust process should focus on application logic while a dedicated reverse proxy terminates TLS, enforces HTTP security headers, compresses responses, and routes traffic across services. Caddy solves this operational bottleneck without sprawling configuration files or external certificate cron jobs.

In this step-by-step tutorial, you will install Caddy on Ubuntu or Debian, write a production-ready Caddyfile with automatic HTTPS and strict security headers, route multiple upstream services including WebSockets, and reload configuration changes without dropping active connections. If you are already planning a single-binary backend stack, pair this setup with our guide on How to Deploy PocketBase to Production on a VPS (systemd + Caddy).

Why Caddy Simplifies TLS and Reverse Proxying on Single-VPS Stacks

Traditional reverse proxy setups often split responsibilities across multiple tools: one daemon to handle HTTP routing, another client such as Certbot to request TLS certificates, and custom reload hooks to ensure the proxy picks up renewed certificates before expiry. When any link in that chain breaks, users see browser security warnings in production.

Caddy collapses that entire lifecycle into a single Go binary with an integrated ACME client. As documented in the Caddy Automatic HTTPS documentation, Caddy automatically obtains and renews TLS certificates from ACME certificate authorities whenever a site block uses a public domain name, and it automatically redirects plain HTTP requests on port 80 to HTTPS on port 443.

Under the hood, certificate issuance relies on the Automated Certificate Management Environment (ACME) standard used by Let’s Encrypt. Caddy handles HTTP-01 and TLS-ALPN-01 domain validation challenges natively, stores certificates on disk under its data directory, and renews them well before expiration without external scripts.

Operational ConcernTraditional Proxy + CertbotCaddy Reverse Proxy
TLS provisioning and renewalSeparate ACME client plus cron or systemd timerBuilt-in ACME client with automatic renewal
HTTP to HTTPS redirectManual server block on port 80Enabled automatically for domain blocks
Configuration verbosityMulti-file virtual hosts and SSL include snippetsConcise Caddyfile syntax per domain
Zero-downtime reloadsSignal reload with manual config test firstBuilt-in validate command and atomic admin API reload

Installing Caddy and Enabling the systemd Service on Ubuntu or Debian

Before installing Caddy, make sure your domain DNS A and AAAA records already point to your server’s public IP addresses, and ensure ports 80 and 443 are open in your firewall (for example, ufw allow 80,443/tcp and ufw allow 443/udp if you want HTTP/3 QUIC traffic to reach Caddy directly). No other service should be listening on port 80 or 443.

On Ubuntu and Debian servers, install Caddy from the official Cloudsmith repository so that apt installs both the binary and a hardened systemd unit file running under a dedicated non-root caddy user.

bash# Install prerequisite packages for signed APT repositories
sudo apt update
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
 
# Add the official Caddy GPG key and repository
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.asc' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
 
# Install Caddy and verify the systemd service is active
sudo apt update
sudo apt install -y caddy
sudo systemctl enable --now caddy
sudo systemctl status caddy --no-pager

The official package creates /etc/caddy/Caddyfile for configuration, stores TLS certificates and OCSP staples inside /var/lib/caddy, and grants the binary CAP_NET_BIND_SERVICE so it can bind ports 80 and 443 without running as root.

Writing a Production Caddyfile with Automatic HTTPS and Security Headers

The Caddy reverse proxy quick-start shows that a working proxy only needs a domain name and a reverse_proxy directive. In production, however, you should wrap that core rule with global operational settings, reusable snippets for security headers, compression, and structured access logs.

Open /etc/caddy/Caddyfile and replace the default placeholder site with a clean configuration tailored to your domain and upstream application port.

bash# Global options applied across the Caddy server
{
	email [email protected]
	servers {
		protocols h1 h2 h3
	}
}
 
# Reusable security headers snippet
(security_headers) {
	header {
		Strict-Transport-Security "max-age=31536000; includeSubDomains"
		X-Content-Type-Options "nosniff"
		X-Frame-Options "DENY"
		Referrer-Policy "strict-origin-when-cross-origin"
		-Server
	}
}
 
app.example.com {
	import security_headers
	encode zstd gzip
 
	log {
		output file /var/log/caddy/app-access.log {
			roll_size 50mb
			roll_keep 5
		}
	}
 
	reverse_proxy 127.0.0.1:3000 {
		health_uri /healthz
		health_interval 15s
		health_timeout 3s
	}
}

What Each Production Directive Does

  • email [email protected] registers an administrative contact with Let’s Encrypt or ZeroSSL so you receive certificate expiration notices if renewal ever fails due to DNS changes.
  • (security_headers) defines a reusable snippet imported across sites, setting HSTS, MIME-sniffing protection, clickjacking defense, and stripping the Server header.
  • encode zstd gzip compresses text, JSON, HTML, CSS, and JavaScript payloads on the fly using Zstandard when supported by the client or gzip otherwise.
  • health_uri /healthz instructs Caddy to probe the backend every 15 seconds so unhealthy instances stop receiving traffic immediately.
  • log writes rotated JSON access logs to /var/log/caddy/app-access.log without filling your root disk.

Notice that you do not need to manually set X-Forwarded-For, X-Forwarded-Proto, or Host headers for standard HTTP backends. Caddy passes appropriate forwarding headers automatically when proxying upstream requests.

Routing Multiple Backends, WebSockets, and Static Assets

Most VPS deployments outgrow a single process quickly. You might host a marketing site as static files, an API backend on port 8080, a WebSocket collaboration server on port 8081, and an admin dashboard under a dedicated subdomain. Caddy handles path-based routing and subdomain virtual hosts inside the same Caddyfile.

Edge caching and reverse proxy infrastructure architecture diagram
Reverse proxy routing and edge caching layer separating public TLS termination from internal application services. Image: Timo Tijhof (CC0), via Wikimedia Commons.

Caddy supports WebSocket upgrades out of the box inside reverse_proxy without extra Upgrade or Connection header boilerplate. When splitting traffic by path prefix, remember that Caddy evaluates handle blocks in mutually exclusive order, and combining a path_regexp matcher with uri strip_prefix routes versioned API prefixes cleanly without matching unrelated paths.

bashapi.example.com {
	import security_headers
	encode zstd gzip
 
	# Route WebSocket traffic to dedicated realtime worker
	handle /ws* {
		reverse_proxy 127.0.0.1:8081
	}
 
	# Strip /v1 prefix if backend expects root paths
	@v1 path_regexp ^/v1(/|$)
	handle @v1 {
		uri strip_prefix /v1
		reverse_proxy 127.0.0.1:8080
	}
 
	# Serve pre-built static assets directly from disk
	handle {
		root * /var/www/frontend/dist
		try_files {path} /index.html
		file_server
	}
}

Serving static assets directly with file_server keeps unnecessary requests away from your application runtime, while try_files {path} /index.html supports client-side single-page application routing cleanly. If you automate deployments from GitHub to your VPS, review our walkthrough on GitHub Actions Deploy to VPS: Secure SSH Pipeline Step by Step to integrate static build uploads with safe proxy reloads.

Validate every Caddyfile change before reloading production traffic; catching a syntax typo or port conflict in dry-run validation takes milliseconds and protects active user sessions.

Reloading Without Downtime and Verifying TLS Certificates

Never edit /etc/caddy/Caddyfile and blindly restart the daemon with systemctl restart. Restarting drops in-flight HTTP and WebSocket connections and interrupts long-lived downloads. Instead, format, validate, and reload Caddy gracefully through its built-in CLI commands.

bash# Format the Caddyfile consistently
sudo caddy fmt --overwrite /etc/caddy/Caddyfile
 
# Validate syntax and adapter output before applying
sudo caddy validate --config /etc/caddy/Caddyfile
 
# Gracefully reload configuration with zero dropped connections
sudo systemctl reload caddy
 
# Verify HTTP-to-HTTPS redirect, TLS handshake, and security headers
curl -I http://app.example.com
curl -sI https://app.example.com | grep -iE 'HTTP/|strict-transport-security|x-content-type-options'

Troubleshooting Common ACME and Proxy Errors

  • Port 80 blocked or occupied: If ACME HTTP-01 challenges fail, inspect sudo ss -tulpn | grep -E ':80|:443' to confirm no stray Nginx or Apache process is bound, and check cloud provider security groups in addition to ufw.
  • 502 Bad Gateway from reverse_proxy: Confirm the upstream process is actually listening on 127.0.0.1 and the configured port, and verify whether systemd or SELinux policies restrict local loopback connections.
  • Cloudflare or upstream CDN loops: When placing a proxy CDN in front of Caddy, ensure the CDN SSL mode uses Full (Strict) so it connects to Caddy over HTTPS rather than triggering an HTTP-to-HTTPS redirect loop.
  • Inspecting live ACME logs: Run sudo journalctl -u caddy -n 100 --no-pager to view certificate issuance events, challenge failures, and upstream health check transitions.

Once your first certificate is issued and verified with curl -sI, Caddy handles ongoing renewals in the background. You get automated TLS, modern HTTP/2 and HTTP/3 transport, clean multi-service routing, and zero-downtime configuration reloads in one small configuration file.

Featured image credit: Dsimic (CC BY-SA 4.0), via Wikimedia Commons.