Caddyfile boilerplate

I find that almost all of my websites in my Caddyfile have some amount of boilerplate that must be included in every entry. I currently deal with that using an import:

# reusable snippets: https://caddyserver.com/docs/caddyfile/concepts#snippets
(boilerplate) {
	encode gzip zstd
	file_server
}

Which I include in each website’s section using import boilerplate.

First of all, is there a more elegant solution?

Second of all, if you find yourself with similar boilerplate sections, what is in your boilerplate?

In Caddy v1, I used the “expires” plugin to set a caching policy on all of my sites, so in Caddy v2 I’ll also probably be setting the headers as recommended in my boilerplate, once I get around to it.

Third, I find myself including a www redirect section for every domain, like this:

# redirect no-www to www
sunrisepvd.com {
	redir https://www.sunrisepvd.com{uri}
}

I don’t think this can go in the boilerplate for every domain section because it seems to need to be its own entry. Also I don’t know how to use variables to make this generic, instead of specific to each site. How would you go about this?

Yep, snippets is the way to do it.

For the www redir, you can do a snippet like this:

(redir-to-www) {
	{args.0} {
		redir https://www.{args.0}{uri}
	}
}

# then later, at the top-level, not in a site block:
import redir-to-www sunrisepvd.com
1 Like