File_server for sub-directory?

1. Caddy version (caddy version):

v2.2.1 h1:Q62GWHMtztnvyRU+KPOpw6fNfeCD3SkwH7SfT1Tgt2c=

2. How I run Caddy:

a. System environment:

ubuntu 20.04

b. Command:

systemctl start caddy

c. Service/unit/compose file:

default systemd file from apt-get install caddy

d. My complete Caddyfile or JSON config:

www.mydomain.com mydomain.com {
    root * /usr/local/www/site
    encode gzip

    rewrite /files     /files/
    file_server

    file_server /files/* {
        browse /usr/local/www/site/files/browse.tpl
    }
    log {
        output file /var/log/caddy/access.log
    }
}

3. The problem I’m having:

Hi all, this is likely an easy question, but how do I get a working directory listing (browse) for a sub-directory of my site? The issue I have now, is that the browse part works, and I can see the listing of files in my sub-directory, but the generated html from the template (default Caddy template) is stripping the prefix off.

So instead of:
https://mydomain.com/files/file1.txt

I am getting:
https://mydomain.com/file1.txt

Apologies for the redaction.

4. Error messages and/or full log output:

N/A

5. What I already tried:

I have tried the handle directive, but that stopped the files from being listed altogether. I’m sure I am just missing something silly and/or not understanding the docs correctly :frowning:

6. Links to relevant resources:

I think the problem is you actually need to issue a redirect rather than a rewrite for /files because otherwise the browser doesn’t know how to build out relative URLs.

redir /files /files/

Credit to @matt for pointing this out to me.

1 Like

Yeah if the directory ends at /files then the browser thinks /files is a file, not a directory. Let Caddy do the redirects that it does by default. (i.e. remove the rewrite).

2 Likes

To clarify, for the redirect to happen automatically, you’ll also need to change your matcher from /files/* to /files*

2 Likes

Thank you both, I had assumed it was just me not quite understanding :slight_smile:

I removed the rewrite and updated /files/* to /files* and everything works as I was hoping for.

2 Likes

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