Universal redirector

Hi, everyone!

I’m trying to create a universal redirector which will redirect any domain from www version to the root domain, so:
http://www.domainhttps://domain
https://www.domainhttps://domain

Then, I would just point any www dns records to caddy.

What I came up with:

:80, :443 {
tls email@email.email {
max_certs 10
}
     redir 301 {
         if {host} starts_with www
         / https://{label2}.{label3}{uri}
}
}

Any improvements? Any help is appreciated!

Looks good. Only a few thoughts:

  • Might not hurt to check for www. instead, in case the subdomain is actually wwwfoo or www2 or something silly that should be separate. (Ninja edit: Actually, you can just check {label1} directly…)

  • You can’t be sure that you’ll have only three labels. Things might get weird if there are more. I’d try something like this instead:

(tls) {
  tls email@example.com {
    max_certs 10
  }
}

http://*.*.*, https://*.*.* {
  import tls
  redir 301 {
    if {label1} is www
    / https://{label2}.{label3}{uri}
  }
}

http://*.*.*.*, https://*.*.*.* {
  import tls
  redir 301 {
    if {label1} is www
    / https://{label2}.{label3}.{label4}{uri}
  }
}

http://*.*.*.*.*, https://*.*.*.*.* {
  import tls
  redir 301 {
    if {label1} is www
    / https://{label2}.{label3}.{label4}.{label5}{uri}
  }
}

That’ll catch all your longer sites (e.g. state gov / educational like to use a lot of labels) and handle them properly.

Hi @Whitestrake , thanks a lot! That looks much more inclusive.

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