Replacing occurrences in placeholders

Is it possible to run regex replacements on placeholders in server blocks?

One use case I have is taking the tls_on_demand ?domain=<domain> query parameter and passing it to consul via a rewrite

# pseudo code

	on_demand_tls {
		ask http://localhost/ask

http://localhost {
    rewrite * “/v1/agent/service/${replace(query.domain, “.”, “_”
   reverse_proxy consul:8500

And another is using the host header in a dynamic upstream block

dynamic srv {
  name  “${replace(host, “.”, “_”)}”

It’s not currently possible to apply replacements to queries, but you could do it with rewrite: Implement `uri query` operations by armadi1809 · Pull Request #6120 · caddyserver/caddy · GitHub once that’s merged.

It might be possible to do it with a two-step rewrite. This might work:

rewrite * /v1/agent/service/{query.domain}
uri replace . _

Edit: this seems to work:

:8881 {
	rewrite * /foo/bar/{query.domain}?
	uri replace . _
	respond {uri}
$ curl -v http://localhost:8881/foo?domain=a.b.c.d.e.f.g


Thanks — that’s great! I’ll probably have to write a module to handle more complex use cases in the future, but for now this is okay.

For posterity, the solution I’m using to check if a service is in the consul catalog {
  rewrite * /v1/catalog/service/{query.domain}?
  uri replace . -

  reverse_proxy consul.service.consul:8500 {
    @not_registered {
      status 200
      header Content-Length 2

    replace_status @not_registered 400

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