Wildcard subdomain to dynamic upstreams

1. The problem I’m having:

No problem as such, I’m looking for some advice on the best approach for this and whether what I’m attempting to do is even possible with Caddy.

I’m looking to build a service that reverse proxies a wildcard subdomain to dynamic upstreams. For example, I have multiple apps running on multiple servers, all apps are served using Caddy but I want to be able to hit: *.ap.viz.co, for this example we will use one.ap.viz.co and I want that to be able to reverse proxy to an app on server 1, then if I hit two.ap.viz.co it is reversed proxied to server 2, etc.

I’m looking to setup the wildcard on a separate server so that I can have one DNS record for the wildcard that points at the proxy server and then that proxies to each individual server dependent on the subdomain.

I’m able to setup Caddy for each app on each server and setup the on_demand_tls for the wildcard subdomain, however I’m unsure how to setup the dynamic upstreams. Or whether this is a recommended approach.

2. Error messages and/or full log output:

Please use the preview pane to ensure it looks nice.


3. Caddy version:

v2.7.6 h1:w0NymbG2m9PcvKWsrXO6EEkY9Ru4FJK8uQbYcev1p3A=

4. How I installed and ran Caddy:

Installed using Homebrew on local machine, but using apt on servers.

a. System environment:

MacOS and Ubuntu

b. Command:

c. Service/unit/compose file:

d. My complete Caddy config:

5. Links to relevant resources:

There’s a bunch of ways to do dynamic upstreams.

If you know the list of upstreams ahead of time, you could use a map directive to match {labels.3} (i.e. the 4th host segment counted from the right) and map it to an upstream, then you can use that map output var as you reverse_proxy upstream.

Or you could implement your own dynamic upstreams module (Caddy has a couple built-in, you could copy the Caddy source code as a basis for your own) to map the hostname to an upstream.