How to Replace Cache-Control value while reverve_proxying Strapi

1. Caddy version (caddy version): 2.3 (image: caddy:2.3.0-alpine)

a. System environment: Docker

d. My complete Caddyfile or JSON config:

api.domain.fi  {
	reverse_proxy strapi:1337
	header /uploads/* Cache-Control max-age=31536000
}

3. The problem I’m having:

Strapi adds cache-control: max-age=0 header to it’s responses for static files in its uploads folder and I would like add cache for those files in api.domain.fi/uploads/ folder.

When I add header to Caddyfile header is added but also old one is kept and order is always so that 0 owerwrites 31536000 in browser.

Header added

header /uploads/* Cache-Control max-age=31536000

Header in Chrome dev tools

cache-control: max-age=31536000
cache-control: max-age=0

5. What I already tried:

I have tried to folllow docs header (Caddyfile directive) — Caddy Documentation and delete existing header and add a new one but then both headers are deleted. I have also tried to replace value for header but then no header exists in response. Using ? mark to add value if not yet exist doesn’t work either.

header -Cache-Control
header /uploads/* Cache-Control max-age=31536000
header /uploads/* Cache-Control max-age=0 max-age=31536000
header /uploads/* Cache-Control "max-age=0" "max-age=31536000"
header /uploads/* ?Cache-Control max-age=31536000

I think you need to use the defer option so your change (using the replacement mode) happens after the proxy.

The Caddyfile adapter sorts directives based on a predetermined order:

The header handler, by default, works by making changes right away to the response headers. If you need to control headers after the proxy runs, then you need to enable defer so that the changes are applied on the way back up the middleware chain, after the response is written.

The alternative is to use the header_down subdirective of the reverse_proxy directive, which works similarly – it will make header modifications on the way back downstream after the request is proxied.

Thank you francislavoie

I actually did try header_down also before, but without success but defer saved the day and solution was finally very simple. (header (Caddyfile directive) — Caddy Documentation)

header /uploads/* Cache-Control max-age=31536000 {
  defer
}
1 Like

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