Common Caddyfile Patterns

This page demonstrates a few complete and minimal Caddyfile configurations for common use cases. These can be helpful starting points for your own Caddyfile documents.

These are not drop-in solutions; you will have to customize your domain name, ports/sockets, directory paths, etc. They are intended to illustrate some of the most common configuration patterns.

Menu

Static file server

  1. example.com
  2. root * /var/www
  3. file_server

As usual, the first line is the site address. The root directive specifies the path to the root of the site (the * means to match all requests, so as to disambiguate from a path matcher)—change the path to your site if it isn’t the current working directory. Finally, we enable the static file server.

Reverse proxy

Proxy all requests:

  1. example.com
  2. reverse_proxy localhost:5000

Only proxy requests having a path starting with /api/ and serve static files for everything else:

  1. example.com
  2. root * /var/www
  3. reverse_proxy /api/* localhost:5000
  4. file_server

PHP

With a PHP FastCGI service running, something like this works for most modern PHP apps:

  1. example.com
  2. root * /var/www
  3. php_fastcgi /blog/* localhost:9000
  4. file_server

Customize the site root and path matcher accordingly; this example assumes PHP is only in the /blog/ subdirectory—all other requests will be served as static files.

The php_fastcgi directive is actually just a shortcut for several pieces of configuration.

Redirect www. subdomain

To add the www. subdomain with an HTTP redirect:

  1. example.com {
  2. redir https://www.example.com{uri}
  3. }
  4. www.example.com {
  5. }

To remove it:

  1. www.example.com {
  2. redir https://example.com{uri}
  3. }
  4. example.com {
  5. }

Trailing slashes

You will not usually need to configure this yourself; the file_server directive will automatically add or remove trailing slashes from requests by way of HTTP redirects, depending on whether the requested resource is a directory or file, respectively.

However, if you need to, you can still enforce trailing slashes with your config. There are two ways to do it: internally or externally.

Internal enforcement

This uses the rewrite directive. Caddy will rewrite the URI internally to add or remove the trailing slash:

  1. example.com
  2. rewrite /add /add/
  3. rewrite /remove/ /remove

Using a rewrite, requests with and without the trailing slash will be the same.

External enforcement

This uses the redir directive. Caddy will ask the browser to change the URI to add or remove the trailing slash:

  1. example.com
  2. redir /add /add/
  3. redir /remove/ /remove

Using a redirect, the client will have to re-issue the request, enforcing a single acceptable URI for a resource.