Skip to content

Caddy snippets and imports for reusable configuration

Using snippets, imports, and named matchers to factor out repetition in a Caddyfile — patterns an MSP keeps in the kitbag for clean, maintainable configs.

A Caddyfile that hosts ten sites with similar boilerplate ends up with the same block copied ten times — security headers, log formats, common matchers. Snippets and imports let you write that boilerplate once and reference it everywhere. This article is the pattern we apply to client Caddyfiles to keep them readable as the site count grows past what a single screen holds.

How to verify

A Caddyfile that uses snippets and imports validates the same as a flat one:

caddy validate --config /etc/caddy/Caddyfile
caddy adapt --config /etc/caddy/Caddyfile --pretty | head -100
caddy fmt /etc/caddy/Caddyfile
ls -la /etc/caddy/sites-enabled/

caddy adapt shows the expanded form — the snippets are resolved and inlined. If the expansion does not show what you expect, the snippet reference is wrong or a wildcard is silently not matching.

What’s happening

The Caddyfile has three reuse primitives:

  1. Snippets. A named block defined at the top level with (name) { ... } (note the parentheses — they are how Caddy knows this is a snippet, not a site). Snippets are not active sites; they only execute when imported.

  2. Imports. The import directive reads another file (or pattern of files) at parse time and inlines the contents. Used at the top level to pull in entire site blocks; used inside a site block to pull in directive sequences.

  3. Named matchers. A reusable filter declared inside a site block with @name { ... }. The name then stands in for the filter elsewhere in the same site block. They are not strictly reuse across sites, but they collapse repeated matcher logic within a site.

All three resolve at parse time — they expand before the JSON adapter runs. The runtime cost is zero; the source is just clearer.

The import directive supports glob patterns (import sites-enabled/*.caddy), positional argument substitution (import mysnippet "first arg" "second"), and recursive imports (a file can import another, which imports another — Caddy stops at a reasonable depth to avoid loops).

The procedure

  1. Extract a snippet for security headers. A pattern used across many sites:

    (security_headers) {
        header {
            Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
            X-Content-Type-Options "nosniff"
            X-Frame-Options "DENY"
            Referrer-Policy "strict-origin-when-cross-origin"
            Permissions-Policy "camera=(), microphone=(), geolocation=()"
        }
    }

    The parentheses on (security_headers) mark this as a snippet, not a site. The snippet itself does nothing until imported.

  2. Use the snippet in site blocks. import pulls the snippet body in:

    example.com {
        import security_headers
        reverse_proxy localhost:3000
    }
    
    docs.example.com {
        import security_headers
        root * /var/www/docs
        file_server
    }

    Both sites get the same headers. Change the snippet once and both sites update on the next reload.

  3. Snippet with arguments. Pass values into the snippet using {args.0}, {args.1}:

    (cache_static) {
        @static path *.css *.js *.woff2 *.png *.jpg *.svg *.webp
        header @static Cache-Control "public, max-age={args.0}, immutable"
    }
    
    example.com {
        import cache_static 31536000
        file_server
    }
    
    staging.example.com {
        import cache_static 3600
        file_server
    }

    Production cache for one year; staging for one hour. Same snippet, different argument.

  4. Split sites across multiple files. When the Caddyfile grows past 200 lines, break it up:

    # /etc/caddy/Caddyfile
    
    {
        email ops@example.com
    }
    
    import snippets/*.caddy
    import sites-enabled/*.caddy
    # /etc/caddy/snippets/security.caddy
    
    (security_headers) {
        header {
            Strict-Transport-Security "max-age=31536000; includeSubDomains"
            X-Content-Type-Options "nosniff"
        }
    }
    # /etc/caddy/sites-enabled/example.com.caddy
    
    example.com {
        import security_headers
        reverse_proxy localhost:3000
    }

    The top-level Caddyfile becomes a manifest; each site has its own file under config management.

  5. Named matchers for in-site reuse. Repeated matchers within a single site:

    api.example.com {
        @auth_required {
            not path /health /metrics /public/*
        }
    
        @write_method method POST PUT PATCH DELETE
    
        handle @auth_required {
            basicauth {
                admin $2a$14$...
            }
        }
    
        reverse_proxy localhost:3000
    
        log {
            output file /var/log/caddy/api.log
        }
    
        header @write_method X-Audit-Required "true"
    }

    @auth_required and @write_method are declared once, used many times — no copy-paste across handle and header blocks.

  6. Conditional imports — environment-specific overlays. Pick a snippet at boot via an environment variable:

    (prod_logging) {
        log {
            output file /var/log/caddy/access.log {
                roll_size 100MiB
                roll_keep 30
            }
            format json
        }
    }
    
    (dev_logging) {
        log {
            output stdout
            format console
        }
    }
    
    example.com {
        import {$CADDY_ENV}_logging
        reverse_proxy localhost:3000
    }

    Run with CADDY_ENV=prod or CADDY_ENV=dev in the systemd unit’s environment file; the snippet name resolves at boot.

Operational notes

  • The import directive uses Go’s filepath.Glob — patterns like *.caddy match the current directory. Recursive globs (**/*.caddy) are not supported; flatten the directory or list explicit imports.
  • Snippet arguments are positional only — no named arguments. If a snippet needs more than two or three values, consider splitting it into multiple smaller snippets.
  • A circular import (snippet A imports B imports A) causes Caddy to fail to validate with a stack-overflow style error. Keep snippet dependencies one-directional.
  • Named matchers are scoped to the site block they appear in. To share a matcher across sites, use a snippet that declares the matcher; the snippet’s matcher is then in scope wherever the snippet is imported.
  • The caddy fmt command formats snippets the same way as sites. Run it after any non-trivial refactor — the parentheses-vs-curly-brace distinction is easy to mess up by hand.

Stack Harbor refactors client Caddyfiles into a snippet-and-imports layout the first time the config exceeds what fits on one screen — common patterns extracted, per-site files under git, environment overlays driven by env vars. If you have a Caddy fleet whose config has accumulated copy-paste over time and you want it consolidated under one operating playbook, this is the kind of work covered by our Managed Operations practice.