Caddy - The Ultimate Web Server
Caddy 2 is a powerful, enterprise-ready, open source web server with automatic HTTPS written in Go.
Import
Imports will incl. snippets or files, replacing this directive with the contents of the snippet or file.
This directive is a special case: it is evaluated before the structure is parsed, it can appear anywhere in the Caddyfile.
Syntax
import <pattern> [<args...>]
is the filename, glob pattern, or name of [snippet][self-znips] to include. - It is an error if a specific file cannot be found.
- However, glob patterns are not errors.
- If file pattern is a filename or glob, it's
always relative to the file the
import
appears in.
- <args...> is an optional list of arguments to pass to the imported tokens.
- They can be used with a placeholder of the form
{args.N}
whereN
is the 0-based positional index of parameter. - This placeholder is a special case & is evaluated at parse-time.
- They can be used with a placeholder of the form
Examples
Import all files in a folder within the same parent directory:
import sites-enabled/*
Import a snippet that sets CORS headers using an import argument:
(cors) {
@origin header Origin {args.0}
header @origin Access-Control-Allow-Origin "{args.0}"
header @origin Access-Control-Allow-Methods "OPTIONS,HEAD,GET,POST,PUT"
}
example.com {
import cors example.com
}
Pro-Tip:
Using the apache standard sites-enabled/
directory with symlinked to
files in sites-available/
is a good way to easily enable/disable
different site routes or in this case Caddy configs.
Within /etc/caddy
create directories sites-enabled/
& sites-available/
.
Then add all Caddyfiles wihtin sites-available/
and
create symlinks inside sites-available/
linking to those files.
Snippets
Snippets are special blocks defined by giving them a name surrounded in parenthesis.
(redirect) {
@http {
protocol http
}
redir @http https://{host}{uri}
}
Then you can reuse this snippet anywhere by using the import
directive:
import redirect
It's also possible to pass arguments to imported configurations & use them like so:
(snippet) {
respond "Yahaha! You found {args.0}!"
}
a.example.com {
import snippet "Example A"
}
b.example.com {
import snippet "Example B"
}