Is there a way with Caddy to proxy a certain domain pattern?

Hey!

I am using Caddy as an entrypoint on my server where I have a backend that handles requests of clients.

I may receive requests from domains like:

So I need a way to redirect all traffic from (assets|files|assets-cdn|files-cdn).*
to my webserver (127.0.0.1:8080).

I tried to use assets.* in my caddyfile for ex. (and replicating other entries) but I get this error when I run caddy reload: “Error: adapting config using caddyfile: subject does not qualify for certificate: ‘assets.*’”.

I know I can redirect all traffic to my webserver but I would like to avoid sending him unnecessary traffic (domain not matching my pattern).

Does someone have any idea on how to put this in place?

Thanks!

How many of these domains do you have? Do you control those domains, or are they owned by other entities?

I don’t know in advance how many domains I will have, basically I ask my clients to create a subdomain of their domain and ask them to points it to my webserver where caddy is running (but this is automatic I am running a SaaS), so I don’t own those domains. This is why I need kind of a regex pattern to match those domains.

I think with nginx you can do something like:

server {
    listen 80;
    server_name ~^(assets|files|assets-cdn|files-cdn)\..+$;

    location / {
        proxy_pass http://localhost:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Another solution would be to match my frontend app.example.com, my backend backend.example.com and redirect all other traffic to backend.example.com (the app that needs to handle the requests of my clients). Do you know how I can do that?

Thank you!

In that case you’re looking for On-Demand TLS:

1 Like

Thanks a lot finally made it work!

For future readers here’s how I’ve implemented it:

{
        on_demand_tls {
                # this endpoint being handled by my backend to accept or deny obtaining
                # a certificate for a given domain name, thereby ensuring that not just any domain 
                # can cause your server to request a certificate and potentially hit Let's Encrypt rate limits.
                # https://caddyserver.com/docs/caddyfile/options#on-demand-tls
                ask "http://127.0.0.1:8080/api/should-sign-cert"
        }
}

backend.example.com {
        reverse_proxy 127.0.0.1:8080
}

app.example.com {
        reverse_proxy 127.0.0.1:3000
}

:80, :443 {
        tls {
                on_demand
        }

        reverse_proxy 127.0.0.1:8080
}

Order of entries is important.

1 Like

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