Dynamically proxy based on subdomain

1. The problem I’m having:

I’ve been running caddy for a couple years now, but I have a very simple setup and still consider myself a beginner so please bear with me.

  • My main use for caddy is turning all my insecure http connections to https connections. It’s not so much a security concern as it is an annoyance to get invalid cert popups and the fact that my browser won’t fill in passwords on insecure http.
  • My network endpoints all use dns (server1. example. com, server2. example. com etc).
  • My caddy server is p. example. com
  • I currently have everything mapped by hand so server1. p. example. com points to server1. example. com

I want to know if its possible to dynamically grab the subdomain “server1” from server1. p. example. com, and forward to server1. example. com

2. Error messages and/or full log output:

N/A

3. Caddy version:

Version 2.8.4

4. How I installed and ran Caddy:

Installed using official guide

a. System environment:

Ubuntu 24.04.1

Yes, of course. Probably could be even simpler than this, but only went ahead and slightly modified an existing config of mine:

https://*.p.example.com {
	@hostprefix vars_regexp hostprefix {host} ^([^.]+)\.
	handle @hostprefix {
		map {re.hostprefix.1} {rp_hostport} {
			~^.*$ "${0}.example.com:80"
		}
		reverse_proxy {rp_hostport}
	}
}
1 Like

You can just use reverse_proxy {labels.3}.example.com :grin:

1 Like

That worked!! Thanks!

Added the following as a catch-all at the end of my caddyfile

handle {
     reverse_proxy {labels.3}.example.com:80
}

It wouldn’t work without the port 80 on the end.
I now realize some of my endpoints are https and some are http. I don’t suppose there is a way for it to automatically check each to see which it should forward to.

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