Mastering Caddy: Real-World Config Examples
Caddy, an open-source, production-grade HTTP/2 web server with automatic HTTPS, is gaining traction due to its modern architecture and features. Understanding how to configure Caddy is crucial for harnessing its full potential. This guide offers practical examples to help you get started with Caddy config files.

Before delving into specific configurations, ensure you have Caddy installed and are familiar with its basic syntax. Caddy's config is written in HCL (HashiCorp Configuration Language), which provides a simple and readable format.

Caddyfile Basics
Caddy uses a single config file, Caddyfile, to manage multiple hosts and services. Let's explore some basic Caddyfile examples.

At the minimum, a Caddyfile must contain a single `@http` block to configure the http server.
Simple HTTP Server Configuration

Here's a basic example of an HTTP server configuration:
@http
{
listen :80
}
In this example, Caddy listens on port 80 for HTTP traffic.
Serving static files

To serve static files, specify the `root` field, pointing to the directory containing your content:
@http
{
root * /path/to/your/site
listen :80
}
Caddy will serve files from the `/path/to/your/site` directory.
Advanced Caddy Configurations

Now let's explore more advanced configurations with reverse proxies and redirects.
Reverse Proxy with Upstream




















Caddy can proxy requests to an upstream server, such as a Node.js or a Go application. You'll need to specify the upstream server details:
:80
{
reverse_proxy http://localhost:3000
}
Here, Caddy proxies requests received on port 80 to the upstream server listening on `http://localhost:3000`.
Custom Headers and Redirects
You can easily add custom headers or redirect requests. Here's an example of adding a custom header:
:80
{
custom_header my_header "My Custom Header Value"
reverse_proxy http://localhost:3000
}
For redirection, use the `redirect` field:
:80
{
redirect https://www.example.com
}
Caddy will redirect all HTTP requests to `https://www.example.com`.
Securing your Website with Caddy
Caddy also excels at securing your website. Let's look at a couple of security-related examples.
Automatic HTTPS with Let's Encrypt
Caddy can automatically obtain and renew Let's Encrypt certificates to enable HTTPS. Here's an example:
:80
{
tls https://example.com
}
Caddy will ensure that only encrypted traffic is allowed on port 80.
Blocking specific file extensions
To prevent serving of specific file types, use the `file_types` field:
:80
{
file_types disable "*.php" "*.asp"
root * /path/to/your/site
}
Caddy now blocks serving of PHP and ASP files.
Mastering Caddy configurations takes practice, but with these examples, you're well on your way. Happy configuring!