caddyserver / website

The Caddy website
156 stars 153 forks source link

Alternative syntax for www. subdomain redirects #416

Closed Cryszon closed 2 months ago

Cryszon commented 2 months ago

I was unable to get Common Caddyfile Patterns page's Redirect www. subdomain working (it caused "too many redirects"), but found this community post with a different syntax that worked.

Before (not working):

www.example.com {
    redir https://example.com{uri}
}

example.com {
}

:80 {
    ...
}

After (working):

:80 {
    @www.example.com host www.example.com
    redir @www.example.com https://example.com{uri}
    ...
}

Maybe the documentation could be updated to include the alternate syntax or replace the current one.

mohammed90 commented 2 months ago

The example on the website doesn't have the :80 site, so the example is still correct. I assume your websites are behind Cloudflare which (based on your Cloudflare configuration) enforces HTTPS before passing the request to Caddy; and Cloudflare connects to Caddy over HTTP, which Caddy rejects to only be connected over HTTPS thus causing redirect loop. If yes, that'd be a very specific situation that is not always applicable.

Cryszon commented 2 months ago

I'm not using Cloudflare, but do have a reverse proxy that handles HTTPS before Caddy. Specifically Coolify, which handles HTTPS and uses Traefik to route requests to a Docker container that's running Caddy.

What is the correct way to handle redirects in this case and are there any other things I should take into consideration with this configuration? Is there some documentation I missed for this specific setup?

mohammed90 commented 2 months ago

You could simply do this:

http://www.example.com {
    redir https://example.com{uri}
}

http://example.com {
 # ...
}