Set header only for some try_files matches

1. Output of caddy version:

v2.5.2 h1:eCJdLyEyAGzuQTa5Mh3gETnYWDClo1LjtQm2q9RNZrs=

2. How I run Caddy:

caddy run -config Caddyfile.prod

a. System environment:

Mac OS 12.5.1

My complete Caddy config:

{
    auto_https off
    http_port 8808
}
:8808 {
    root * /srv/app/public
    try_files {path} /index.html
    encode zstd gzip
    file_server
    log
    respond /health 200
}

3. The problem I’m having / what I already tried

I’m trying to add different cache header depending on whether the requested path or index.html will be returned:

index.html => cache-control: no-store
else => cache-control: max-age: 31536000

I played around with

    header /index.html {
        Cache-Control "no-store"
    }

    header {
        Cache-Control "max-age=31536000"
    }

but I only got no-store when there was index.html in the request.

But I need to have no-store whenever index.html will be returned, i.e. the requested path does not exist on the file system.

Is this possible?

header is matched before try_files is run because it’s higher on the directive order.

If you want it to happen after the try_files rewrite, then there’s 3 different ways you can override the order things execute in.

  • Wrap it up in a route to override the order for that one case
  • Use the order global option to move try_files to run before header (this may have other side effects, keep that in mind)
  • Use handle blocks to set up mutually exclusive routes – handle runs after try_files so that could do fine as well.
1 Like

Thanks for your response!

For everyone else looking for THE solution:

    route {
        try_files {path} /index.html
        header /index.html {
            Cache-Control "no-store"
        }
    }

    header {
        Cache-Control "max-age=31536000"
    }
1 Like