### Install caddy Manpages
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Example of how to generate, compress, and install Caddy manpages on a Linux system. This process makes Caddy documentation accessible via the `man` command.
```bash
$ caddy manpage --directory man
$ gzip -r man/
$ sudo cp man/* /usr/share/man/man8/
$ sudo mandb
```
--------------------------------
### Multiple Servers with Templated Body
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Demonstrates starting multiple Caddy respond servers with templated bodies, showing how to use server number, port, and address variables within the response. This example also shows how to pipe content into the command.
```bash
caddy respond --listen :2000-2004 "{{printf \"I'm server {{.N}} on port {{.Port}}\"}}"
```
--------------------------------
### WinSW Service Configuration Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
An example XML configuration file for setting up Caddy as a Windows service using WinSW.
```xml
caddy
Caddy Web Server (powered by WinSW)
Caddy Web Server (https://caddyserver.com/)
%BASE%\caddy.exe
run
yyyy-MM-dd
```
--------------------------------
### Start Prometheus Server
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/metrics.md
Start the Prometheus server using the specified configuration file. This command assumes the prometheus binary is in your PATH.
```bash
$ prometheus --config.file=prometheus.yaml
```
--------------------------------
### Start Caddy Server
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/quick-starts/caddyfile.md
Run the Caddy server from the directory containing your Caddyfile. This command starts Caddy with the specified configuration.
```bash
caddy start
```
--------------------------------
### php_fastcgi with Docker Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/php_fastcgi.md
An example demonstrating php_fastcgi configuration within a Docker environment, highlighting the use of a different root directory for the PHP upstream.
```caddy
example.com {
root * /app
php_fastcgi localhost:9000 {
root /var/www/html
}
}
```
--------------------------------
### Full Caddyfile Example with handle_path
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/handle_path.md
A complete Caddyfile example showing how handle_path can be used to serve an API while other directives serve static content. Note that handle_path and handle are mutually exclusive.
```caddy
example.com {
# Serve your API, stripping the /api prefix
handle_path /api/* {
reverse_proxy localhost:9000
}
# Serve your static site
handle {
root /srv
file_server
}
}
```
--------------------------------
### Install Caddy on OPNsense
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Installs the Caddy package on OPNsense systems using the pkg command.
```shell
pkg install os-caddy
```
--------------------------------
### Full Caddyfile Global Options Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/options.md
This snippet shows a comprehensive example of global options in a Caddyfile, including general, TLS, server, filesystem, PKI, and event configurations. It demonstrates the structure and variety of settings available.
```caddy
{
# General Options
debug
http_port
https_port
default_bind
order first|last|[before|after ]
storage {
}
storage_clean_interval
admin off| {
origins
enforce_origin
}
persist_config off
log [name] {
output ...
format ...
level
include
exclude
}
grace_period
shutdown_delay
metrics {
per_host
observe_catchall_hosts
otlp
}
# TLS Options
auto_https off|disable_redirects|ignore_loaded_certs|disable_certs
email
default_sni
fallback_sni
local_certs
skip_install_trust
acme_ca
acme_ca_root
acme_eab {
key_id
mac_key
}
acme_dns ...
dns ...
ech {
dns ...
}
on_demand_tls {
ask
permission
}
key_type ed25519|p256|p384|rsa2048|rsa4096
cert_issuer ...
renew_interval
cert_lifetime
ocsp_interval
ocsp_stapling off
renewal_window_ratio
preferred_chains [smallest] {
root_common_name
any_common_name
}
# Server Options
servers [] {
name
listener_wrappers {
}
timeouts {
read_body
read_header
write
idle
}
keepalive_interval
keepalive_idle
keepalive_count
0rtt off
trusted_proxies ...
trusted_proxies_strict
trusted_proxies_unix
client_ip_headers
trace
max_header_size
enable_full_duplex
log_credentials
protocols [h1|h2|h2c|h3]
strict_sni_host [on|insecure_off]
}
# File Systems
filesystem {
}
# PKI Options
pki {
ca [] {
name
root_cn
intermediate_cn
intermediate_lifetime
maintenance_interval
renewal_window_ratio
root {
format
cert
key
}
intermediate {
format
cert
key
}
}
}
# Event options
events {
on
}
}
```
--------------------------------
### Memory Profile (Heap Allocation) Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/profiling.md
This snippet displays a memory profile, tracking heap allocations. It's useful for identifying memory-intensive parts of the program. The format is similar to goroutine profiles but starts with allocation information.
```go
0: 0 [1: 4096] @ 0xb1fc05 0xb1fc4d 0x48d8d1 0xb1fce6 0xb184c7 0xb1bc8e 0xb41653 0xb4105c 0xb4151d 0xb23b14 0x4719c1
# 0xb1fc04 bufio.NewWriterSize+0x24 bufio/bufio.go:599
# 0xb1fc4c golang.org/x/net/http2.glob..func8+0x6c golang.org/x/net@v0.17.0/http2/http2.go:263
# 0x48d8d0 sync.(*Pool).Get+0xb0 sync/pool.go:151
# 0xb1fce5 golang.org/x/net/http2.(*bufferedWriter).Write+0x45 golang.org/x/net@v0.17.0/http2/http2.go:276
# 0xb184c6 golang.org/x/net/http2.(*Framer).endWrite+0xc6 golang.org/x/net@v0.17.0/http2/frame.go:371
# 0xb1bc8d golang.org/x/net/http2.(*Framer).WriteHeaders+0x48d golang.org/x/net@v0.17.0/http2/frame.go:1131
# 0xb41652 golang.org/x/net/http2.(*writeResHeaders).writeHeaderBlock+0xd2 golang.org/x/net@v0.17.0/http2/write.go:239
# 0xb4105b golang.org/x/net/http2.splitHeaderBlock+0xbb golang.org/x/net@v0.17.0/http2/write.go:169
# 0xb4151c golang.org/x/net/http2.(*writeResHeaders).writeFrame+0x1dc golang.org/x/net@v0.17.0/http2/write.go:234
```
--------------------------------
### Build Caddy from Source
Source: https://github.com/caddyserver/website/blob/master/src/includes/quick-assist/content.md
Builds Caddy from source using Go. Requires Git and Go to be installed.
```bash
git clone "https://github.com/caddyserver/caddy.git"
cd caddy/cmd/caddy/
go build
```
--------------------------------
### Get Entire Configuration
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/api.md
Retrieves the entire Caddy configuration and pretty-prints it. This is useful for backing up or inspecting the current setup.
```APIDOC
## GET /config/
### Description
Retrieves the entire Caddy configuration.
### Method
GET
### Endpoint
/config/
### Response
#### Success Response (200)
- **(object)** - The complete Caddy configuration object.
### Response Example
```json
{
"apps": {
"http": {
"servers": {
"myserver": {
"listen": [
":443"
],
"routes": [
{
"match": [
{
"host": [
"example.com"
]
}
],
"handle": [
{
"handler": "file_server"
}
]
}
]
}
}
}
}
}
```
```
--------------------------------
### Install Caddy using Webi
Source: https://github.com/caddyserver/website/blob/master/src/includes/quick-assist/content.md
Installs Caddy using the Webi installer script on Linux, macOS, and Windows.
```bash
curl -sS https://webi.sh/caddy | sh
```
```powershell
curl.exe https://webi.ms/caddy | powershell
```
--------------------------------
### Start Caddy with a JSON Configuration File
Source: https://github.com/caddyserver/website/blob/master/src/index.html
Starts the Caddy server using a specified JSON configuration file. This is useful for automated deployments and managing configurations programmatically.
```bash
$ caddy start --config caddy.json
```
--------------------------------
### Start `go tool pprof`
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/profiling.md
This command opens an interactive prompt for analyzing a profile. Replace 'profile' with your actual file path if different.
```bash
go tool pprof profile
```
--------------------------------
### Install Caddy Windows Service with WinSW
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
Installs Caddy as a Windows service using the WinSW executable.
```bash
caddy-service install
```
--------------------------------
### Install Caddy using Webi on Linux/macOS
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Webi to install Caddy on Linux and macOS. This is a community-maintained installation method.
```bash
curl -sS https://webi.sh/caddy | sh
```
--------------------------------
### xcaddy Build Import Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy.md
An example of how `xcaddy` internally manages module compilation. It creates a Go module that requires Caddy and your plugin, adding an import statement to ensure your module is compiled in.
```go
import _ "github.com/example/mymodule"
```
--------------------------------
### Install Caddy on Gentoo
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use the emerge package manager to install Caddy on Gentoo systems. This is a community-maintained installation method.
```bash
emerge www-servers/caddy
```
--------------------------------
### Install Caddy with Scoop on Windows
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Scoop to install Caddy on Windows. This is a community-maintained installation method.
```powershell
scoop install caddy
```
--------------------------------
### Install Caddy on Debian/Ubuntu (Testing)
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Installs Caddy from the testing Cloudsmith repository, which includes betas and release candidates. This method also sets up Caddy as a systemd service.
```bash
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-testing-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/testing/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-testing.list
sudo chmod o+r /usr/share/keyrings/caddy-testing-archive-keyring.gpg
sudo chmod o+r /etc/apt/sources.list.d/caddy-testing.list
sudo apt update
sudo apt install caddy
```
--------------------------------
### HTTP Handler Module Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy.md
A complete example of an HTTP handler module that writes the visitor's IP address to a specified output stream. It demonstrates module registration, Caddyfile configuration parsing, and implementation of Caddy interfaces.
```go
package visitorip
import (
"fmt"
"io"
"net/http"
"os"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
func init() {
caddy.RegisterModule(Middleware{})
httpcaddyfile.RegisterHandlerDirective("visitor_ip", parseCaddyfile)
}
// Middleware implements an HTTP handler that writes the
// visitor's IP address to a file or stream.
type Middleware struct {
// The file or stream to write to. Can be "stdout"
// or "stderr".
Output string `json:"output,omitempty"`
w io.Writer
}
// CaddyModule returns the Caddy module information.
func (Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.visitor_ip",
New: func() caddy.Module { return new(Middleware) },
}
}
// Provision implements caddy.Provisioner.
func (m *Middleware) Provision(ctx caddy.Context) error {
switch m.Output {
case "stdout":
m.w = os.Stdout
case "stderr":
m.w = os.Stderr
default:
return fmt.Errorf("an output stream is required")
}
return nil
}
// Validate implements caddy.Validator.
func (m *Middleware) Validate() error {
if m.w == nil {
return fmt.Errorf("no writer")
}
return nil
}
// ServeHTTP implements caddyhttp.MiddlewareHandler.
func (m Middleware) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
m.w.Write([]byte(r.RemoteAddr))
return next.ServeHTTP(w, r)
}
// UnmarshalCaddyfile implements caddyfile.Unmarshaler.
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
d.Next() // consume directive name
// require an argument
if !d.NextArg() {
return d.ArgErr()
}
// store the argument
m.Output = d.Val()
return nil
}
// parseCaddyfile unmarshals tokens from h into a new Middleware.
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
var m Middleware
err := m.UnmarshalCaddyfile(h.Dispenser)
return m, err
}
// Interface guards
var (
_ caddy.Provisioner = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
)
```
--------------------------------
### Caddyfile Example with Tracing
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/tracing.md
A Caddyfile example demonstrating the tracing directive within handle blocks, including setting custom request headers with trace IDs.
```caddyfile
example.com {
handle /api* {
tracing {
span api
}
request_header X-Trace-Id {http.vars.trace_id}
reverse_proxy localhost:8081
}
handle {
tracing {
span app
span_attributes {
user_id {http.request.cookie.user-id}
}
}
reverse_proxy localhost:8080
}
}
```
--------------------------------
### Install Caddy on Windows
Source: https://github.com/caddyserver/website/blob/master/src/includes/quick-assist/content.md
Installs Caddy on Windows using Chocolatey or Scoop package managers.
```bash
choco install caddy
```
```bash
scoop install caddy
```
--------------------------------
### Install Caddy on Debian/Ubuntu
Source: https://github.com/caddyserver/website/blob/master/src/includes/quick-assist/content.md
Installs Caddy using apt on Debian-based systems. Requires adding the Caddy repository and GPG key.
```bash
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy
```
--------------------------------
### Install Caddy on Debian/Ubuntu (Stable)
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Installs Caddy from the stable Cloudsmith repository. This method automatically sets up Caddy as a systemd service.
```bash
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https curl
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg
sudo chmod o+r /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy
```
--------------------------------
### Registering an HTTP Caddyfile Adapter
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy/config-adapters.md
Example of how to register a Caddyfile adapter specifically for the HTTP server type in Go.
```go
func init() {
caddyconfig.RegisterAdapter("caddyfile", caddyfile.Adapter{ServerType: ServerType{}})
}
```
--------------------------------
### Start Simple HTTP Servers
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Starts simple, hard-coded HTTP servers useful for development and debugging. Servers can be configured with custom status codes, headers, and bodies. The listen address can be specified, including port ranges for multiple servers.
```bash
caddy respond
[-s, --status ]
[-H, --header ": "]
[-b, --body ]
[-l, --listen ]
[-v, --debug]
[--access-log]
[]
```
```bash
caddy respond
```
```bash
caddy respond "Hello, world!"
```
```bash
caddy respond \
--listen :80 \
--status 503 \
--header "Content-Type: text/html"
```
--------------------------------
### Verifying Caddy Binary Installation
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
After moving the Caddy binary, run this command to confirm that the installation was successful and the binary is executable.
```bash
caddy version
```
--------------------------------
### Example: Match Non-Existent Header
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/response-matchers.md
An example of using the 'header' matcher with a '!' prefix to match responses that do not have the 'Foo' header field.
```caddy-d
@not_foo header !Foo
```
--------------------------------
### Install Custom Caddy Binary
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/build.md
This sequence of commands installs a custom Caddy binary, setting it up to be managed by the alternatives system alongside the default package version. It ensures the custom binary is prioritized.
```bash
sudo dpkg-divert --divert /usr/bin/caddy.default --rename /usr/bin/caddy
sudo mv ./caddy /usr/bin/caddy.custom
sudo update-alternatives --install /usr/bin/caddy caddy /usr/bin/caddy.default 10
sudo update-alternatives --install /usr/bin/caddy caddy /usr/bin/caddy.custom 50
sudo systemctl restart caddy
```
--------------------------------
### OpenTelemetry Exporter Configuration via Environment Variables
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/tracing.md
Example environment variables for configuring the OpenTelemetry OTLP exporter endpoint and headers.
```bash
export OTEL_EXPORTER_OTLP_HEADERS="myAuthHeader=myToken,anotherHeader=value"
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://my-otlp-endpoint:55680
```
--------------------------------
### Serve Static Files from Current Directory
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/quick-starts/static-files.md
Run this command in your terminal in the root directory of your website to start a static file server.
```bash
caddy file-server
```
--------------------------------
### Implement Provisioner Interface
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy.md
Implement the Provisioner interface to perform setup tasks for your module. This is also where you should set default values and load guest modules.
```go
func (g *Gizmo) Provision(ctx caddy.Context) error {
// TODO: set up the module
return nil
}
```
--------------------------------
### Rekor Log Entry Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/signature-verification.md
An example JSON output from the Rekor CLI, detailing a verified log entry including signature, public key, and metadata.
```json
{
"Attestation": "",
"AttestationType": "",
"Body": {
"HashedRekordObj": {
"data": {
"hash": {
"algorithm": "sha256",
"value": "508f1044ecd9f14c43c6c8986b45b90fc79f25736e2bc85c0911433ce82533f2"
}
},
"signature": {
"content": "MEUCIHGL2HP5XzcUESTxIk72FS1aNK54LesTfyo+dVhRMeduAiEAnWZDZ5Ur44Y9056vr4to2Fb9FteG53eAFotv3fUZ4h4=",
"publicKey": {
"content": "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSURsRENDQXhtZ0F3SUJBZ0lVSXJCRm5hM1hWSmhuWnJmZU1RSHZTZ0tyKzJBd0NnWUlLb1pJemowRUF3TXcKTnpFVk1CTUdBMVVFQ2hNTWMybG5jM1J2Y21VdVpHVjJNUjR3SEFZRFZRUURFeFZ6YVdkemRHOXlaUzFwYm5SbApjbTFsWkdsaGRHVXdIaGNOTWpJd09USXdNVGN4TnpBMldoY05Nakl3T1RJd01UY3lOekEyV2pBQU1Ga3dFd1lICktvWkl6ajBDQVFZSUtvWkl6ajBEQVFjRFFnQUVJdTcyc1lVYzNzK1FIWkYxTnNTQ25WUmU4NlpiUHhpSmlndmUKMkpOOEFrQTVBTlJPR1Fzd2s4eWswTjgxOTdFSUpJblBPamdHLzVKMUJvUzFuaVdNbXFPQ0FqZ3dnZ0kwTUE0RwpBMVVkRHdFQi93UUVBd0lIZ0RBVEJnTlZIU1VFRERBS0JnZ3JCZ0VGQlFjREF6QWRCZ05WSFE0RUZnUVVPOERSCjBzaTZMVldWSDJoNDNNWXMyYlVYRHVvd0h3WURWUjBqQkJnd0ZvQVUzOVBwejFZa0VaYjVxTmpwS0ZXaXhpNFkKWkQ4d1lRWURWUjBSQVFIL0JGY3dWWVpUYUhSMGNITTZMeTluYVhSb2RXSXVZMjl0TDJOaFpHUjVjMlZ5ZG1WeQpMMk5oWkdSNUx5NW5hWFJvZFdJdmQyOXlhMlpzYjNkekwzSmxiR1ZoYzJVdWVXMXNRSEpsWm5NdmRHRm5jeTkyCk1pNDJMakF3T1FZS0t3WUJCQUdEdnpBQkFRUXJhSFIwY0hNNkx5OTBiMnRsYmk1aFkzUnBiMjV6TG1kcGRHaDEKWW5WelpYSmpiMjUwWlc1MExtTnZiVEFTQmdvckJnRUVBWU8vTUFFQ0JBUndkWE5vTURZR0Npc0dBUVFCZzc4dwpBUU1FS0RneU1XRXdPR0UyWlRNNVpXUXdaVGRqTkROaU1ESTNNV05qWmpFeU5tTXhPVFJsWWpZek16a3dGUVlLCkt3WUJCQUdEdnpBQkJBUUhVbVZzWldGelpUQWZCZ29yQmdFRUFZTy9NQUVGQkJGallXUmtlWE5sY25abGNpOWoKWVdSa2VUQWVCZ29yQmdFRUFZTy9NQUVHQkJCeVpXWnpMM1JoWjNNdmRqSXVOaTR3TUlHS0Jnb3JCZ0VFQWRaNQpBZ1FDQkh3RWVnQjRBSFlBQ0dDUzhDaFMvMmhGMGRGcko0U2NSV2NZckJZOXd6alNiZWE4SWdZMmIzSUFBQUdEClcrZEVVd0FBQkFNQVJ6QkZBaUVBbkQ1TlJLWmhGTGhDSEhESXpWNmJ3VkFxbFlQNmRXMEN3S1dEbzFqem1FWUMKSUU1WmVlSzE0b2k2SSs3ejJWUlhTVnE0L3IxNUdBRnhZYUNNRnJJMFVPampNQW9HQ0NxR1NNNDlCQU1EQTJrQQpNR1lDTVFDK3N6d1ZWbmhreGcrOFNHbXBDaWZOVFpJNUFGQkNxQ3F0RVUxazhtRTE3QWpwdFdvVUcvYkJEa2J1Cm9GUUlKdUVDTVFDbmJaZmJUTWpkUnhNOUtIcW04MlJRTEZxZG5SRFF6Mi9RNlRkMi9jeU9uY05ydW5nSFFHcEEKMXR2Mmw5VnFOcDA9Ci0tLS0tRU5EIENFUlRJRklDQVRFLS0tLS0K"
}
}
}
},
"LogIndex": 3618623,
"IntegratedTime": 1663694226,
"UUID": "04deb84e5a73ba75ea69092c6d700eaeb869c29cae3e0cf98dbfef871361ed09",
"LogID": "c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d"
}
```
--------------------------------
### Caddyfile Comment Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile-tutorial.md
Add comments to your Caddyfile by starting a line with a hash symbol '#'. Comments are ignored during parsing and are useful for notes and explanations.
```caddyfile
# this starts a comment
```
--------------------------------
### Basic JSON Configuration for Apps
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy.md
An example of the top-level JSON structure for Caddy configuration, showing the 'apps' property where app modules are defined.
```json
{
"apps": {}
}
```
--------------------------------
### Pull Caddy Docker Image
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Docker to pull the official Caddy image from Docker Hub. This is a quick way to get started with Caddy in a containerized environment.
```bash
docker pull caddy
```
--------------------------------
### Multi-line Expression Matcher with Heredoc
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/matchers.md
Uses heredoc syntax to define a multi-line CEL expression for the 'api' matcher. It matches requests where the method is 'GET' and the path starts with '/api/'.
```caddy-d
@api <
Caddy tutorial
Page loaded at: {{`{{`}}now | date "Mon Jan 2 15:04:05 MST 2006"{{`}}`}}
```
--------------------------------
### Get Local PKI CA Certificate Chain
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/api.md
Fetches the certificate chain for the default local PKI CA. This is used internally by `caddy trust` to install the root certificate into system trust stores.
```bash
curl "http://localhost:2019/pki/ca/local/certificates"
```
```text
-----BEGIN CERTIFICATE-----
MIIByDCCAW2gAwIBAgIQViS12trTXBS/nyxy7Zg9JDAKBggqhkjOPQQDAjAwMS4w
...
By75JkP6C14OfU733oElfDUMa5ctbMY53rWFzQ==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIBpDCCAUmgAwIBAgIQTS5a+3LUKNxC6qN3ZDR8bDAKBggqhkjOPQQDAjAwMS4w
...
9M9t0FwCIQCAlUr4ZlFzHE/3K6dARYKusR1ck4A3MtucSSyar6lgRw==
-----END CERTIFICATE-----
```
--------------------------------
### Implement Placeholder Support in Provisioning (Go)
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy/placeholders.md
Example of using `caddy.NewReplacer()` in the `Provision` step to replace global placeholders. This happens during configuration loading, before requests are processed.
```go
func (g *Gizmo) Provision(ctx caddy.Context) error {
repl := caddy.NewReplacer()
g.Name = repl.ReplaceAll(g.Name,"")
return nil
}
```
--------------------------------
### Start a Static File Server
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Spins up a static file server with various configuration options. It can serve files over HTTP or HTTPS, enable directory browsing, and render templates.
```bash
caddy file-server
-r, --root
[--listen ]
-d, --domain
-b, --browse
[--reveal-symlinks]
-t, --templates
[--access-log]
-v, --debug
-f, --file-limit
[--no-compress]
-p, --precompressed
```
--------------------------------
### Install Caddy with Chocolatey on Windows
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Chocolatey to install Caddy on Windows. This is a community-maintained installation method.
```powershell
choco install caddy
```
--------------------------------
### Install Caddy with Homebrew on Mac
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Homebrew to install Caddy on macOS. This is a community-maintained installation method.
```bash
brew install caddy
```
--------------------------------
### Build Caddy from Source
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/build.md
Navigate to the Caddy build directory and compile the binary using the Go build command. This method does not embed version information by default.
```bash
cd caddy/cmd/caddy/
go build
```
--------------------------------
### Example .env File for Caddy
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
Format for an environment variables file used with the EnvironmentFile directive. Do not include quotes around the values.
```env
CF_API_TOKEN=super-secret-cloudflare-tokenvalue
```
--------------------------------
### JSON Configuration After Caddyfile Adaptation
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy/placeholders.md
Shows the resulting JSON configuration after adapting the Caddyfile example, highlighting how `{$HOST}` is replaced while `{env.HOST}` remains.
```json
{
"apps": {
"http": {
"servers": {
"srv0": {
"listen": [":8080"],
"routes": [
{
"handle": [
{
"body": "example",
"handler": "static_response",
"status_code": 200
}
]
}
]
},
"srv1": {
"listen": [":8081"],
"routes": [
{
"handle": [
{
"body": "{env.HOST}",
"handler": "static_response",
"status_code": 200
}
]
}
]
}
}
}
}
}
```
--------------------------------
### Create Caddy Windows Service with sc.exe
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
Use the sc.exe command to create a new Windows service for Caddy, setting it to start automatically.
```bash
sc.exe create caddy start= auto binPath= "YOURPATH\caddy.exe run"
```
--------------------------------
### Basic Caddyfile Configuration
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/getting-started.md
A simple Caddyfile to serve 'Hello, world!' on port 2015. Save this to a file named 'Caddyfile'.
```caddyfile
:2015
respond "Hello, world!"
```
--------------------------------
### Install Caddy on Termux
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use the pkg package manager to install Caddy on Termux. This is a community-maintained installation method.
```bash
pkg install caddy
```
--------------------------------
### Install Caddy using Ansible
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Ansible Galaxy to install the Caddy role. This is a community-maintained installation method.
```bash
ansible-galaxy install nvjacobo.caddy
```
--------------------------------
### Cacheable GET Responses
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/header.md
Marks successful responses (status 2xx) to GET requests as cacheable for up to an hour. This uses a named matcher '@GET' and a response matcher for the status code.
```caddy-d
@GET method GET
header @GET Cache-Control "max-age=3600" {
match status 2xx
}
reverse_proxy upstream:443
```
--------------------------------
### Serve Files with Precompression
Source: https://github.com/caddyserver/website/blob/master/src/includes/examples/file-server.md
Use this snippet to serve files from a directory while also serving precompressed versions (e.g., .gz, .br) if they exist. This improves performance by avoiding on-the-fly compression.
```caddy
file_server /downloads/* {
precompressed
}
```
--------------------------------
### Start Caddy Windows Service
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
Command to start the Caddy Windows service after it has been created.
```bash
sc.exe start caddy
```
--------------------------------
### Import snippet with multiple arguments for proxy upstreams
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/import.md
This example imports an 'https-proxy' snippet and passes a list of IP addresses as arguments to configure multiple reverse proxy upstreams. The `{args[:]}` placeholder inserts all provided arguments.
```caddy
(https-proxy) {
reverse_proxy {args[:]} {
transport http {
ls
}
}
}
example.com {
import https-proxy 10.0.0.1 10.0.0.2 10.0.0.3
}
```
--------------------------------
### Print Build Information
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Displays build-related information, including the main module path and package versions.
```bash
caddy build-info
```
--------------------------------
### Start Caddy Container
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/running.md
Starts the Caddy service defined in your Docker Compose file in detached mode.
```bash
docker compose up -d
```
--------------------------------
### Automate Certificates using JSON Configuration
Source: https://github.com/caddyserver/website/blob/master/src/index.html
This example demonstrates how to automate certificate provisioning using Caddy's JSON configuration API. It shows the structure for defining sites and their certificate management settings.
```json
{
"apps": {
"http": {
"servers": {
"my_server": {
"listen": [":443"],
"routes": [
{
"match": [{"host": ["example.com"]}],
"handle": [{"handler": "static_response", "body": "Hello, world!"}]
}
]
}
}
},
"tls": {
"automation": {
"policies": [
{
"issuers": [{"module": "acme"}],
"on_demand": true
}
]
}
}
}
}
```
--------------------------------
### Example: Match Successful Status Codes
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/response-matchers.md
An example of using the 'status' matcher to identify successful responses (2xx).
```caddy-d
@success status 2xx
```
--------------------------------
### Install Latest Caddy with Mise
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Uses the mise tool version manager to install the latest global version of Caddy.
```shell
mise use -g caddy@latest
```
--------------------------------
### Build Caddy with Plugins using xcaddy
Source: https://github.com/caddyserver/website/blob/master/src/includes/quick-assist/content.md
Builds Caddy from source with custom plugins using the xcaddy tool. Basic build and build with specific plugins are shown.
```bash
xcaddy build
```
```bash
xcaddy build \
--with github.com/caddyserver/nginx-adapter
--with github.com/caddyserver/ntlm-transport@v0.1.1
```
--------------------------------
### Install kraft CLI
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Installs the kraft CLI tool, a companion to Unikraft. This is the first step for using Caddy with Unikraft.
```shell
curl --proto '=https' --tlsv1.2 -sSf https://get.kraftkit.sh | sh
```
--------------------------------
### Run Caddy with Caddyfile Configuration
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/getting-started.md
Start Caddy directly using a Caddyfile in the current directory or specified via the --config flag. Caddy automatically adapts the Caddyfile to JSON.
```bash
caddy run
```
```bash
caddy run --config /path/to/Caddyfile
```
--------------------------------
### Build Caddy with Plugins using xcaddy
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/build.md
Build Caddy with custom plugins by specifying their import paths using the --with flag in xcaddy. Plugin versions can be customized using @ syntax.
```bash
xcaddy build \
--with github.com/caddyserver/nginx-adapter
--with github.com/caddyserver/ntlm-transport@v0.1.1
```
--------------------------------
### Build Caddy with xcaddy
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/build.md
Use the xcaddy command-line tool to build Caddy, which automatically embeds version information. Ensure xcaddy is installed and in your PATH.
```bash
xcaddy build
```
--------------------------------
### Start Plaintext HTTP Proxy (Command Line)
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/quick-starts/reverse-proxy.md
Use the `caddy reverse-proxy` command to quickly set up a plaintext HTTP proxy from a specified port to a backend service. This is suitable for simple production requirements.
```bash
caddy reverse-proxy --from :2080 --to :9000
```
--------------------------------
### Install Caddy on Fedora
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use DNF to install Caddy on Fedora systems. This involves enabling the Caddy COPR repository first.
```bash
dnf install dnf5-plugins
dnf copr enable @caddy/caddy
dnf install caddy
```
--------------------------------
### Download CPU Profile
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/profiling.md
To download a CPU profile, make a request to the /debug/pprof/profile endpoint. Specify the duration in seconds using the 'seconds' query parameter. The collected profile will be downloaded as a binary file named 'profile'.
```bash
curl "http://localhost:8080/debug/pprof/profile?seconds=30" > profile
```
--------------------------------
### Serve Website using Caddyfile Configuration
Source: https://github.com/caddyserver/website/blob/master/src/index.html
This snippet shows how to configure Caddy to serve a website using the Caddyfile format. It's a concise way to set up production-ready sites.
```caddyfile
www.example.com {
# Enable compression and HTTP/2.
protocols h2c
# Set this directory to serve static files.
root *
/static
# Enable the static file server.
file_server
}
```
--------------------------------
### Skip Trust Store Installation
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/options.md
Skips the automatic installation of the local CA's root certificate into system and browser trust stores.
```caddy
{skip_install_trust
}
```
--------------------------------
### Basic Caddyfile Example
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile.md
A production-ready Caddyfile serving a WordPress site with managed HTTPS. It sets the document root, enables compression, configures PHP FastCGI, and enables the file server.
```caddy
example.com {
root /var/www/wordpress
encode
php_fastcgi unix//run/php/php-version-fpm.sock
file_server
}
```
--------------------------------
### Install Caddy on CentOS/RHEL
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use DNF to install Caddy on CentOS and RHEL systems. This involves enabling the Caddy COPR repository first.
```bash
dnf install dnf-plugins-core
dnf copr enable @caddy/caddy
dnf install caddy
```
--------------------------------
### Basic Caddyfile Configuration for Static Files
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/quick-starts/static-files.md
Create a Caddyfile in your site's root directory with this content to serve static files on localhost.
```caddy
localhost
file_server
```
--------------------------------
### Start Caddy in the Background
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Starts Caddy as a background process. It returns once the process is running or fails. Use `caddy stop` or the API to exit.
```bash
caddy start
-c, --config
-a, --adapter
[--envfile ]
[--pidfile ]
-w, --watch
```
--------------------------------
### Example: Match Header with Multiple OR Values
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/response-matchers.md
An example of using the 'header' matcher to match responses where the 'Foo' header is either 'bar' or 'baz'.
```caddy-d
@foo {
header Foo bar
header Foo baz
}
```
--------------------------------
### Implement Placeholder Support During Request Handling (Go)
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy/placeholders.md
Example of fetching a replacer from the request context in `ServeHTTP` to process both global and per-request placeholders like `{http.request.uri}`.
```go
func (g *Gizmo) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
_, err := w.Write([]byte(repl.ReplaceAll(g.Name,"")))
if err != nil {
return err
}
return next.ServeHTTP(w, r)
}
```
--------------------------------
### Using Custom Certificate and Key Files
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/directives/tls.md
Specify the paths to custom PEM-encoded certificate and private key files. Both the certificate and key file paths must be provided.
```caddy
tls
```
--------------------------------
### Get CPU Profile for a Specific Duration
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/profiling.md
Specify the duration in seconds using the `?seconds=` GET parameter to collect a CPU profile for a defined period.
```text
http://localhost:2019/debug/pprof/profile?seconds=30
```
--------------------------------
### Server Options with Bind Directive Mismatch and Match
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/caddyfile/options.md
Demonstrates how `servers` options only apply when the `listener_address` exactly matches the bind address and port. The first example shows a non-matching configuration, while the second shows a successful match.
```caddyfile
{
# This will NOT match the server, bind address missing
servers :8080 {
name private
}
# This will work because it's an exact match
servers 192.168.1.2:8080 {
name public
}
}
:8080 {
bind 127.0.0.1
}
:8080 {
bind 192.168.1.2
}
```
--------------------------------
### Install Caddy using Webi on Windows
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/install.md
Use Webi with PowerShell to install Caddy on Windows. You may need to adjust firewall rules for non-localhost connections.
```powershell
curl.exe https://webi.ms/caddy | powershell
```
--------------------------------
### Calculate Median Response Size for Successful GET Requests
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/metrics.md
This query calculates the median response size in bytes for successful GET requests on a specific handler.
```PromQL
histogram_quantile(0.5, caddy_http_response_size_bytes_bucket{method="GET", handler="file_server", code="200"})
```
--------------------------------
### Define a Basic HTTP Server Configuration
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/api-tutorial.md
A JSON configuration for Caddy defining an HTTP server that responds with 'Hello, world!' to all requests.
```json
{
"apps": {
"http": {
"servers": {
"example": {
"listen": [":2015"],
"routes": [
{
"handle": [{
"handler": "static_response",
"body": "Hello, world!"
}]
}
]
}
}
}
}
}
```
--------------------------------
### Caddyfile with Environment Variable and Placeholder
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/extending-caddy/placeholders.md
Demonstrates the difference between Caddyfile environment variable substitution `{$HOST}` and a global placeholder `{env.HOST}`.
```caddyfile
:8080 {
respond {$HOST} 200
}
:8081 {
respond {env.HOST} 200
}
```
--------------------------------
### Get Goroutine Profile with Debug Parameter
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/profiling.md
Use the `?debug=2` query parameter to get a more verbose goroutine stack dump, similar to unrecovered panic output.
```text
http://localhost:2019/debug/pprof/goroutine?debug=2
```
--------------------------------
### Get Help for a caddy Command
Source: https://github.com/caddyserver/website/blob/master/src/docs/markdown/command-line.md
Use `caddy help` to display CLI help text. You can optionally specify a subcommand to get help for a specific command.
```bash
caddy help [<command>]
```