As we all know, the Web server is an indispensable basic service for Web development and is often used in development. Familiar open source Web servers are the well-known Apache, the powerful Nginx. The open source project we are going to introduce today is written in Go the up-and-coming “: Caddy It has a download without installation can be used, zero configuration to achieve HTTPS and other characteristics, so in many excellent Web server to occupy a place.

Out-of-the-box web server

In this era of HTTPS must-have, Caddy with no additional configuration automatically HTTPS, HTTPS site in minutes to complete the build, making it the preferred server for small and medium Web services. Caddy is very popular among open source enthusiasts, and has collected 42 thousand stars since it was open sourced in 2014.

Caddy

1. Caddy Features

Caddy is a powerful, scalable platform for your sites, services and applications.

Use Caddy to quickly deploy http(s) sites or reverse proxy services on Linux, Mac, Windows. The following features are supported.

  • HTTP/1.1 and HTTP/2
  • Both HTTPS automatic issuance and manual management are accepted
  • Virtual hosting (multiple sites working on a single port)
  • Native IPv4 and IPv6 support
  • Static file distribution
  • Smooth restart/reload
  • Reverse proxy (HTTP or WebSocket)
  • Load balancing and health checks
  • Markdown rendering
  • File browsing service
  • etc.

Compared to traditional Nginx or Apache, Caddy has only one executable file, easy to install and less likely to have strange dependencies, a clear configuration file structure and simple syntax, and a modular architecture that allows you to quickly develop extensions using the Go language.

  • Easy configuration with the Caddyfile
  • Powerful configuration with its native JSON config
  • Dynamic configuration with the JSON API
  • Config adapters if you don’t like JSON
  • Automatic HTTPS by default
    • ZeroSSL and Let’s Encrypt for public names
    • Fully-managed local CA for internal names & IPs
    • Can coordinate with other Caddy instances in a cluster
    • Multi-issuer fallback
  • Stays up when other servers go down due to TLS/OCSP/certificate-related issues
  • Production-ready after serving trillions of requests and managing millions of TLS certificates
  • Scales to tens of thousands of sites … and probably more
  • HTTP/1.1, HTTP/2, and experimental HTTP/3 support
  • Highly extensible modular architecture lets Caddy do anything without bloat
  • Runs anywhere with no external dependencies (not even libc)
  • Written in Go, a language with higher memory safety guarantees than other servers
  • Actually fun to use
  • So, so much more to discover

2. Caddy Tools Installation

Using an Ubuntu machine, introducing automatic installation and manual installation!

Caddy

  • Docker

    1
    2
    
    # https://hub.docker.com/_/caddy
    $ docker pull caddy
    
  • Automatic installation

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    
    # Debian, Ubuntu, Raspbian
    $ 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
    
    # Fedora, RedHat, CentOS
    $ dnf install 'dnf-command(copr)'
    $ dnf copr enable @caddy/caddy
    $ dnf install caddy
    
  • Manual compilation

    1
    2
    3
    4
    
    # Go 1.17 or newer
    $ git clone "https://github.com/caddyserver/caddy.git"
    $ cd caddy/cmd/caddy/
    $ go build
    
  • Manual Download

    1
    2
    3
    4
    5
    
    # https://caddyserver.com/download
    $ mv caddy_linux_amd64 caddy
    $ sudo chmod a+x caddy
    $ mv caddy /bin/caddy
    $ caddy version
    

The caddy installed by command line apt tool will generate part of the configuration file by itself, this way the service will be started after the installation is completed and will start automatically when booting.

  • Configuration file

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    
    # Service boot-up configuration
    /lib/systemd/system/caddy.service.
    
    # Configuration file contents
    $ cat /lib/systemd/system/caddy.service
    [Service]
    ExecStart=/usr/bin/caddy run --environ --config /etc/caddy/Caddyfile
    ExecReload=/usr/bin/caddy reload --config /etc/caddy/Caddyfile --force
    
    # The main configuration file for service startup
    $ cat /etc/caddy/Caddyfile
    :80 {
            # Set this path to your site's directory.
            root * /usr/share/caddy
    
            # Enable the static file server.
            file_server
    
            # Another common task is to set up a reverse proxy:
            # reverse_proxy localhost:8080
    }
    
  • Binary file

    1
    2
    
    # caddy
    /usr/bin/caddy
    

3. Getting Started with Caddy

After the installation is complete, a brief introduction to basic usage!

Here we will start with Caddy common commands, then we will explain the configuration, and finally we will show you how to use Caddy to configure your website and go online with a real case.

  • Common Commands

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    
    $ caddy
    Caddy is an extensible server platform.
    
    usage:
    caddy <command> [<args...>]
    
    commands:
    adapt           指定配置文件 Adapts a config to Caddy native JSON
    add-package     添加扩展 Adds Caddy packages (EXPERIMENTAL)
    build-info      输出build信息 Prints information about this build
    environ         展示环境Prints the environment
    file-server     启动文件服务 Spins up a production-ready file server
    fmt             格式配置文件 Formats a Caddyfile
    hash-password   生成Hash密码 Hashes a password and writes base64
    help            帮助 Shows help for a Caddy subcommand
    list-modules    列出已安装模块 Lists the installed Caddy modules
    reload          重载配置并重启 Changes the config of running Caddy instance
    remove-package  删除扩展 Removes Caddy packages (EXPERIMENTAL)
    reverse-proxy   启动反向代理 A quick and production-ready reverse proxy
    run             启动服务(前台) Starts the Caddy process
    start           启动服务(后台) Starts the Caddy process
    stop            停止服务 Gracefully stops a started Caddy process
    trust           添加信任 Installs a CA cert into local trust stores
    untrust         删除信任 Untrusts a locally-trusted CA certificate
    upgrade         升级版本 Upgrade Caddy (EXPERIMENTAL)
    validate        校验配置是否合法 Tests whether a config file is valid
    version         输出版本信息 Prints the version
    
    Use 'caddy help <command>' for more information about a command.
    
    Full documentation is available at:
    https://caddyserver.com/docs/command-line
    

    The native configuration file of Caddy is in JSON format, but it provides Caddyfile as an interface for users to quickly configure site information, and at runtime Caddy will automatically convert Caddyfile configuration information to JSON configuration file. Caddyfileis not as powerful as aJSON` configuration file, but it is sufficient for users who do not need complex configuration.

  • Configuration file

    1
    2
    3
    4
    5
    
    # matcher stands for matcher
    # If provided, this directive will only respond to the resource described by matcher
    directive [<matcher>] <args...> {
        subdirective [<args...>] # Sub-directives
    }
    
  • File Structure

    File Structure

4. Caddy Simple Demo

Simple demo to explain configuration file writing and command tool usage

The following will demonstrate how to build a site with Caddy and deepen your understanding of the configuration format and command usage.

1
2
3
4
5
6
# 目录结构
.
├──&nbsp;Caddyfile
├──&nbsp;index.html
└──&nbsp;public
&nbsp;&nbsp;&nbsp;&nbsp;└──&nbsp;HG.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!--&nbsp;index.html&nbsp;-->
<!DOCTYPE html>
<html lang="en">
  <head>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <meta charset="UTF-8" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <title>Hello&nbsp;World!</title>
  </head>
  <body>
    &nbsp;&nbsp;&nbsp;&nbsp;你好,世界!
  </body>
</html>

<!--&nbsp;HG.html&nbsp;-->
<!DOCTYPE html>
<html lang="en">
  <head>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <meta charset="UTF-8" />
    &nbsp;&nbsp;&nbsp;&nbsp;
    <title>HelloGitHub</title>
  </head>
  <body>
    &nbsp;&nbsp;&nbsp;&nbsp;HelloGitHub
  </body>
</html>
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Caddyfile

http://localhost:3000 {
    basicauth /public/* {
        # 匹配localhost:3000/public/*的请求为加上登陆保护
        # 用户名HG密码HelloGitHub
        # 密码使用 caddy hash-passowrd 指令生成
        HG JDJhJDE0JGxxxBNGJt
    }

    # 设置当前站点根目录为当前文件夹,*表示匹配所有的请求
    root * ./
    templates

    # 配置当前站点为静态文件服务器,可用于博客系统的搭建
    file_server {
        # 隐藏所有的 .git 文件
        hide .git
    }
}

:4000 {
    # 配置反向代理(匹配请求转发到)
    reverse_proxy /public/* http://localhost:3000
}
1
2
3
4
5
6
7
# 启动服务
$&nbsp;caddy&nbsp;run

# 测试
http://localhost:3000
http://localhost:3000/public/HG.html
http://localhost:4000

In addition to an easy-to-understand configuration file approach, Caddy also provides interfaces for managing configuration. These interfaces make it easy to automate Web server administration, integrate releases and other advanced features.

  • POST /load Set or replace the active configuration
  • POST /stop Stop the active configuration and exit the process
  • GET /config/[path] Export the configuration to the specified path
  • POST /config/[path] Set or replace object; append to array
  • PUT /config/[path] Create a new object or insert into an array
  • PATCH /config/[path] Replace an existing object or array element
  • DELETE /config/[path] Delete the value of the specified path
  • Use @id in JSON to easily traverse the configuration structure
  • GET /reverse_proxy/upstreams Returns the current state of the configured proxy upstream

json

5. Caddy Domain Encryption

From scratch HTTPS site

  • Step 1: Install, use the command described above to install

  • Step 2: Set the domain name resolution address, set it in the website where you bought the domain name, set A record.

    1
    2
    
    # It takes a few minutes for the settings to take effect, so you can check if they take effect with the following command
    $ curl&nbsp;"https://cloudflare-dns.com/dns-query?name=caddy.escapelife.site&type=A"&nbsp;-H&nbsp;"accept:&nbsp;application/dns-json"
    
  • Step 3 : Create the configuration file Caddyfile without the additional setting of HTTPS.

    1
    2
    3
    4
    
    # Domain names and access returns
    caddy.escapelife.site
    
    respond&nbsp;"Hello HTTPS!"
    
  • Step 4 : Start and see the results

    1
    2
    3
    
    # Execute the command in the same directory
    # Visit&nbsp;caddy.escapelife.site&nbsp;to check the effect
    $ sudo caddy run
    

6. Summary

At this point you should have some idea about Caddy. Although its performance is not as good as Nginx, if we talk about how easy it is to get started, Caddy is much easier than Nginx. The main thing is that it is so convenient to enable HTTPS by default, you can open your website HTTPS for free, quickly and easily without having to worry about anything.