Here's an example Caddyfile:
:80 {
root /var/www/html
file_server browse
}
:443 {
tls /path/to/your/cert.pem /path/to/your/key.pem
root /var/www/html
file_server browse
}
example.com {
reverse_proxy 127.0.0.1:8080
}
sub.example.com {
proxy /api 127.0.0.1:8081 {
header_up Host {host}
}
}
Let me break it down:
What is a Caddyfile?
A Caddyfile is a configuration file for the Caddy web server. It's used to define how Caddy should handle incoming requests, serve files, and proxy requests to other servers.
Syntax
The Caddyfile uses a simple syntax, with each block defining a specific configuration. The syntax is as follows:
[address] {
[directive] [arguments]
}
Directives
Here are some common directives used in the example Caddyfile:
root: specifies the directory where Caddy should look for files to serve.
file_server: enables file serving for the current block. The browse argument enables directory browsing.
tls: enables TLS (HTTPS) encryption for the current block. You need to provide the paths to your certificate and private key files.
reverse_proxy: proxies incoming requests to another server.
proxy: proxies incoming requests to another server, with more fine-grained control over the proxying process.
header_up: sets a header on the proxied request.
Blocks
The example Caddyfile has four blocks:
:80: defines the configuration for HTTP requests (port 80). It serves files from /var/www/html and enables directory browsing.
:443: defines the configuration for HTTPS requests (port 443). It serves files from /var/www/html, enables directory browsing, and uses TLS encryption.
example.com: defines a reverse proxy configuration for the example.com domain. It proxies incoming requests to 127.0.0.1:8080.
sub.example.com: defines a proxy configuration for the sub.example.com domain. It proxies incoming requests to 127.0.0.1:8081 and sets the Host header on the proxied request.
How it works
When Caddy starts, it reads the Caddyfile and applies the configurations defined in each block. When a request is received, Caddy checks the blocks to determine which configuration to apply. For example, if a request is received for http://example.com, Caddy will apply the configuration defined in the :80 block. If a request is received for https://sub.example.com/api, Caddy will apply the configuration defined in the sub.example.com block and proxy the request to 127.0.0.1:8081.