Serve file for specific path otherwise redir

1. Caddy version (caddy version):

v2.2.1

2. How I run Caddy:

Caddy installed via apt-get (Ubuntu)
Using a Caddyfile

a. System environment:

Ubuntu 18

b. Command:

sudo caddy run

d. My complete Caddyfile or JSON config:

mysite.co.uk {
  
    handle /.well-known/pki-validation/* {
        root * /home/ubuntu/pki-validation/
        file_server {
            index index.txt
        }
    }

    redir https://www.mysite.co.uk{uri} 302
}

3. The problem I’m having:

We use Caddy as a simple redirect server - redirecting requests for non-www domains to www domains that are hosted elsewhere (for Cloudfront reasons).

This all works fine.

However, I want requests for http://mysite.co.uk/.well-known/pki-validation/VALIDATIONCODE.txt to not be redirected and to remain on http and non-www.

I thought maybe the best way of accomplishing this was to serve a static file inside the Caddy server /home/ubuntu/pki-validation/index.txt but I couldn’t seem to get this working - it still ends up redirecting to https://www.mysite.co.uk/.well-known/pki-validation/VALIDATIONCODE.txt

Any pointers would be greatly appreciated.

Thanks

5. What I already tried:

Initially I tried without the handle directive and had something like:

mysite.co.uk {
    file_server /.well-known/pki-validation/VALIDATIONCODE.txt {
        root /home/ubuntu/pki-validation/
        index index.txt
    }

    redir https://www.mysite.co.uk{uri} 302
}

with no luck

Well, do you literally want the static part to remain on http, not https? Because as written the site will switch to https first unless you specify mysite.co.uk:80. In that case you will also need a second virtual server for mysite.co.uk:443 if you want to handle https as well.

Then note that by default the redir will be executed before the file_server, regardless of the lexical order. To force the order to be significant, enclose the directives in a route { … } block.

So you might try something along the lines of:

mysite.co.uk:80 {
    route {
        file_server /.well-known/pki-validation/VALIDATIONCODE.txt {
            root /home/ubuntu/pki-validation/
            index index.txt
        }
        redir https://www.mysite.co.uk{uri} 302
    }
}
mysite.co.uk:443 {
    redir https://www.mysite.co.uk{uri} 302
}

Paul

1 Like

Thanks so much! I shall give that a try. Many thanks!

Another thing to note, file_server takes the defined root and appends the request path to it, when looking for files on disk. So you may end up with doubled up path segments. To deal with this, use handle_path instead of handle, which bundles in path stripping logic (i.e. removes the matched path prefix) before handing the rest.