Question about applying global headers via snippets

1. The problem I’m having:

I have a fairly generic set of header and subheader directives applied to a majority of my domains/subdomains. Right now, I’m storing them in a snippet along with my custom Porkbun DNS TLS directive:

(headers) {
	encode gzip
	header Content-Security-Policy "upgrade-insecure-requests"
}

(subheaders) {
	header_up X-Real-IP {remote}
	header_down Strict-Transport-Security max-age=31536000
}

(porkbun) {
	tls {
		dns porkbun {
			api_key {env.PORKBUN_API_KEY}
			api_secret_key {env.PORKBUN_API_SECRET_KEY}
		}
	}
}

This is how most of the subdomains look as a result:

sftp.mydomain.com {
	import headers
    import porkbun
	reverse_proxy sftpgo:8080 {
		import subheaders
	}
}

Is there any way to format the subheader snippet so that I can add it to the same location as ‘headers’ and ‘porkbun’ so I don’t have to create so many additional lines in my Caddyfile and keep it easy to read at a glance?

For example:

sftp.mydomain.com {
	import headers
	import porkbun
    import subheaders
	reverse_proxy sftpgo:8080
}

Or is there altogether a better way I should be approaching this?

2. Error messages and/or full log output:

N/A

3. Caddy version:

Latest

4. How I installed and ran Caddy:

docker compose

a. System environment:

b. Command:

N/A

c. Service/unit/compose file:

N/A

d. My complete Caddy config:

N/A

5. Links to relevant resources:

Howdy @halpdesk, I think you can indeed simplify this if you use arguments to your import directives.

Take a look at the examples on import (Caddyfile directive) — Caddy Documentation, especially this one:

Import a snippet which takes a list of proxy upstreams as arguments:

(https-proxy) {
	reverse_proxy {args[:]} {
		transport http {
			tls
		}
	}
}

example.com {
	import https-proxy 10.0.0.1 10.0.0.2 10.0.0.3
}

You could write your reverse proxy out with the header subdirectives included, defining the upstream as an argument, and importing your reverse-proxy-with-subheaders snippet on one line with the upstreams specified per site.

1 Like

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