SOLVED - Rewrite https and nonwww to www

I’m trying to redirect http //site.com, http //www.site.com and https //site.com to https //www.site.com with the following simple caddyfile:
https://site.com https://site.com { redir to https://www.site.com bind 10.0.0.0 root /var/www/html/ }

But https //site.com does not redirect to https //www.site.com
What am I doing wrong? According to https://caddyserver.com/docs/redir it should work: “To create a permanent, “catch-all” redirect, omit the from value:”

A few concerns and suggestions regarding your setup:

  1. Multiple sites should be comma-space delimited as per Caddyfile documentation
  2. Your two sites are the same
  3. If you remove the scheme (https://), Caddy will automatically handle HTTP → HTTPS redirection
  4. In the redir directive docs, to and from are not literal; they should be swapped out for actual values - the 2nd example on the page you linked is relevant to what you’re attempting
  5. Your redir directive may create a loop if this vhost is used for the entire config

With that in mind, I propose an alternate Caddyfile:

site.com, www.site.com {
    redir 301 { # Permanent redirect specified for clarity
        if {host} starts_with site.com # Only redir if there's no www
        / https://www.site.com{uri} # Preserve request URI
    }
    bind 10.0.0.0
    root /var/www/html
}
3 Likes

Thanks for your answer, @Whitestrake!

Regarding point 1 and 2: these were just copy-paste errors I made when asking the question.
I did not know about point 3, thanks! And after rereading the docs on redir your point 4 is obvious now.

Anyway with your proposed configuration its working perfectly now!

Thank you!

1 Like

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