How to setup Caddy to cache some files that could be CDNed

fyi this is more howto … can this be moved to General?

In relation to

Since I was playing around with my home setup and I do notice that the JS, CSS and some assets could be cacheable based on their URL namely.

  • if it has a v= query parameter
  • ends with .chunk.mjs or .chunk.css

So I used my modified Caddy to add a few things such as OTEL tracing support and cache-handler (you can skip the Otel stuff if you don’t need it, but it helps with visualizing the path things go through on Grafana.net)

FROM caddy:builder-alpine AS builder
RUN --mount=type=cache,target=/go/pkg/mod/cache xcaddy build \
  --with github.com/caddyserver/caddy/v2=github.com/trajano/caddy/v2@otel-client \
  --with github.com/caddyserver/cache-handler \
  --with github.com/darkweak/storages/redis/caddy

FROM caddy:alpine
COPY --from=builder /usr/bin/caddy /usr/bin/caddy

Once you have it built the Caddyfile changes are (note I am pretty sure there’s a way of refactoring out the common parts but for now I just repeated the reverse proxy part over and over again.

{
	cache {
		redis {
			url redis:6379
		}
		key {
			disable_scheme # since it won't matter whether it is HTTPS or not, so it shrinks the keys a bit.
		}
	}
}

your.cloud.net {
	header {
		Strict-Transport-Security: "max-age=31536000; includeSubDomains;"
		Referrer-Policy "no-referrer-when-downgrade"
	}
	@vQuery {
		query v=*
	}

	@chunkMjs {
		path *.chunk.mjs
	}

	@chunkCss {
		path *.chunk.css
	}
	handle @vQuery {
		cache {
			mode bypass_request
		}
		reverse_proxy nextcloud:80 {
			header_up X-Real-IP {http.request.remote.host}
			health_uri /ocs/v2.php/apps/serverinfo/api/v1/info
			health_headers {
				NC-Token yourtoken
			}
		}
	}

	handle @chunkCss {
		cache {
			mode bypass_request
		}
		reverse_proxy nextcloud:80 {
			header_up X-Real-IP {http.request.remote.host}
			health_uri /ocs/v2.php/apps/serverinfo/api/v1/info
			health_headers {
				NC-Token yourtokensample
			}
		}
	}
	handle @chunkMjs {
		cache {
			mode bypass_request
		}
		reverse_proxy nextcloud:80 {
			header_up X-Real-IP {http.request.remote.host}
			health_uri /ocs/v2.php/apps/serverinfo/api/v1/info
			health_headers {
				NC-Token yourtokensample
			}
		}
	}

	reverse_proxy nextcloud:80 {
		header_up X-Real-IP {http.request.remote.host}
		health_uri /ocs/v2.php/apps/serverinfo/api/v1/info
		health_headers {
			NC-Token yourtokensample
		}
	}
}