Redirecting HTTP to HTTPS when " auto_https off" is set

1. Caddy version (v2.4.0):

2. How I run Caddy:

I run caddy using a simple Dockerfile:

➜  fly-proxy git:(main) cat Dockerfile 
FROM caddy:2.4.0-alpine
COPY ./Caddyfile /etc/caddy/Caddyfile%

a. System environment:

On fly.io which takes Docker images and runs them as firecracker micro VMs.

b. Command:

The default entrypoint of the docker image is the cmd that is running caddy.

c. Service/unit/compose file:

d. My complete Caddyfile or JSON config:

{   
    debug
    
    auto_https off
    
    admin 0.0.0.0:2019
}

:80 {
    log {
       level DEBUG
       output stderr
    }

    respond "I'm healthy!" 200
}

http://{$DOMAIN}, http://www.{$DOMAIN} {
    reverse_proxy main.internal:80
}

http://payments.{$DOMAIN}, http://payment.{$DOMAIN} {
    reverse_proxy payments.internal:8080
}

http://wages.{$DOMAIN} {
    reverse_proxy wages.internal:8080
}

3. The problem I’m having:

As you can see I have turned off HTTPS in my configuration file. This because my provider https://fly.io handles TLS termination for me. What they don’t do is redirect all the HTTP traffic to HTTPS for me. Somehow my apps have to handle it themselves.
They do send an X-Forwarded-Proto header from upstream with either HTTPS if they have handled TLS termination or HTTP if they haven’t. My question is how would I use the redir directive to redirect http:// to https:// while letting the platform handle the TLS certificates for me.

4. Error messages and/or full log output:

5. What I already tried:

I tried to find a way to handle this within the confines of the platform: https://community.fly.io/t/https-redirect-with-fly-toml/1519

6. Links to relevant resources:

You can use this header value as the flag. You need to look into the concept of Request Matchers in Caddy, specifically the header matcher.

The redir directive takes a matcher and will only be applied if the request matches the given condition.

In your case, you will probably have something like this:

@http header X-Forwarded-Proto HTTP

redir @http https://{http.request.host}{uri} permanent
1 Like

Since I cannot create this outside of site block do I need to adapt my site blocks from:

http://{$DOMAIN}, http://www.{$DOMAIN} {}

to

https://{$DOMAIN}, https://www.{$DOMAIN} {}

No, you said fly.io already handles TLS termination for you. The segment I shared goes inside of a site block, not outside it.

2 Likes

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