Dynamic request(Host) conditions for redirect www

Hey everyone, love Caddy but I’m new to it.

dev.com {
     redir https://www.dev.com

dinesh.com {
     redir https://www.dinesh.com

hopper.com {
     redir https://www.hopper.com

testing.com {
     redir https://www.testing.com



This is my Caddyfile.

I want the following things

  1. want to check domain has sub-domain or not

  2. If domain has sub-domain and then do nothing

  3. If does not have sub-domain then add www and redirect to it

How to use conditions in Caddyfile?

How to check dynamic(host) request?

Hi Dinesh,

something like this

new.example.com, other.example.com, www.example.com, example.com {
        @canonicalHosts not host www.example.com
        redir @canonicalHosts https://www.example.com{uri}

Hi Bernd,

What should I do if multiple hosts with multiple sub-domains?

Our application provides domain configuration for end users. End user points their A/AAAA to our address. Now we have a dynamic host requests.
Like, dev.com, dinesh.com, hopper.com and testing.com.

So Now what I need is need to check the incoming request.

# * means all incoming requests ( dev.com, dinesh.com, hopper.com and testing.com )
* {
if {host.sub_domain} is 'www'
redirect_to https://www.{host}{uri}
redirect_to https://{host}{uri}

This is not right code but I want like this instead of mention all our end user domains because we have 100+ different domains

Take a look at some background for on-demand-tls at this great documentation: Serving tens of thousands of domains over HTTPS with Caddy

You can then also combine other matchers like host, header_regexp or maps to achive what you want and redirect on demand.

1 Like

You can use the {labels.*} placeholders to grab a specific part of the hostname, where * is the index starting from the right, so {labels.0} is com, {labels.1} is example and {labels.2} is www.

So you could do something like:

@not-www not header_regexp Host ^www\.
redir @not-www https://www.{labels.1}{labels.0}{uri}
1 Like