If/else (conditional) on Caddy V2?

Hi. I have been searching for a while for the usage of if/else. I found a couple of posts made a few years back, but there is no recent post about this.

How do I use if/else in Caddy V2? Is there a documentation for it? Because i cannot find any. Can Caddy V2 even use if/else?

Thank you!

Use request matchers. What kind of logic are you looking to implement?

I have multiple domains that I frequently changing their subdomain.

Let say I got these domains:

I want to redirect example.com/.net/.org and all subdomains to ww10

Something like, if subdomain is not ww10, redirect to ww10

I think I got it.

    @redirect {
        expression `{http.request.host.labels.2} != "ww10"`
    }
    redir @redirect https://ww10.{http.request.host.labels.1}.{http.request.host.labels.0}

But can I specify example.com and *.example.com without writing them both? Tried *example.com with no luck

You can shorten the placeholders to {labels.2}, see the placeholder shortcuts available in the Caddyfile:

You can use a header_regexp Host matcher instead of the host matcher to match the hostname how you want.

The host matcher does not cross label boundaries with *, by design, to match certificate matching logic.

Thanks a lot!

1 Like

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