Proxy to different endpoint depending on subdomain

I am using caddy to serve homepage of an application, a front-end vue.js application, and an api. Here is the caddyfile. This works fine.

example.com {
tls off
root ./home
gzip
}

app.example.com {
root ./frontend
tls off
log / stdout "{combined} /// {label1} {uri}"
errors stdout
}

api.example.com {
tls off
proxy / 0.0.0.0:3000/api
}

I want to route to a different endpoint depending on the subdomain. Tried this first:

proxy / localhost:3000/{label1}

This proxies to backend with %7Blabel1%7D instead of the subdomain. Tried many other ways. Then I thought probably rewrite will help.

*.example.com {

rewrite {username}.example.com /proxy/{username}

proxy /proxy/{username} localhost:3000/{username}{uri} {
   without /proxy/
}

}

If I test with test.example.com, it returns a 404 error.

Is there a way to route to a different endpoint depending on subdomain?

Hi @jjude,

It looks like your attempts were made on a couple of incorrect assumptions. Firstly, proxy upstreams can’t have placeholders, they have to be static. Secondly, rewrite doesn’t act on the URL, it acts on the requested path (e.g., for example.com/foo/bar, the rewrite directive acts on /foo/bar).

The only way to route to a different endpoint based on a subdomain is to enumerate your subdomains and endpoints.

foo.example.com {
  proxy / foo
}

bar.example.com {
  proxy / bar
}

# etc...

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