How to write a elegant reverse_proxy Caddyfile

1. Caddy version (caddy version):

v2.4.3

2. How I run Caddy:

Systemd

a. System environment:

Ubuntu 18.04

b. Command:

/usr/local/bin/caddy run --environ --config /data/conf/caddy/Caddyfile

c. Service/unit/compose file:

[Unit]
Description=Caddy
Documentation=https://caddyserver.com/docs/
After=network.target network-online.target
Requires=network-online.target

[Service]
Type=notify
User=root
Group=root
ExecStart=/usr/local/bin/caddy run --environ --config /data/conf/caddy/Caddyfile
ExecReload=/usr/local/bin/caddy reload --config /data/conf/caddy/Caddyfile
TimeoutStopSec=5s
LimitNOFILE=1048576
LimitNPROC=512
PrivateTmp=true
ProtectSystem=full
AmbientCapabilities=CAP_NET_BIND_SERVICE

[Install]
WantedBy=multi-user.target

3. The problem Iā€™m having:

I replaced Nginx with Caddy as a reverse proxy.

This is architecture of my site:

  • /static/* is for static files like javascript and css
  • /media/* is for static files which is uploaded by user, like avatar images
  • /admin/* is a administrator panel, which is in the 127.0.0.1:8080
  • /*, the rest of the pages is the user interface, which is in the 127.0.0.1:8081

These things in the Nginx is like that:

server {
    listen 80;
    server_name example.com;
    location ~ /(static|media)/ {
        root /data/;
        expires 30d;
    }

    location /admin/ {
        proxy_pass 127.0.0.1:8080;
    }

    location / {
        proxy_pass 127.0.0.1:8081;
    }

}

But the Caddyfile is difficult to understand rather than Nginx (for me), and how to write a elegant configuration for my Caddy server?

Pretty simple:

example.com {
	@static path /static/* /media/*
	handle @static {
		root * /data
		file_server
	}

	handle /admin/* {
		reverse_proxy 127.0.0.1:8080
	}

	handle {
		reverse_proxy 127.0.0.1:8081
	}
}
  • Named matcher @static with a path matcher for those two static file locations

  • Inline path matcher for /admin/*

  • handle blocks to implement mutual exclusivity between each (similar to location in nginx) with the last one without a matcher being fallback

1 Like

Thank you, it works!

1 Like

This topic was automatically closed after 30 days. New replies are no longer allowed.