caddyfile格式简单,相比nginx的配置文件,的确简约好多,caddyfile一共有39条指令,分别学习下:

一、 abort

立即终止对连接,前端实际实际上是任何请求都不会获取的,像下面的例子:

Caddyfile:

:18080 {
  abort
}
root@iv-ydxlc2pz40cva4fg2yxm:~# curl -I http://localhost:18080
curl: (7) Failed to connect to localhost port 18080 after 0 ms: Couldn't connect to server

常见的场景:

  1. 对特定的上下文停止响应
#cat Caddyfile
:18080 {
 respond "hello 18080"
 
 @deny path /admin /api
 abort @deny
}

效果:

root@iv-ydxlc2pz40cva4fg2yxm:~# curl -I http://localhost:18080
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Server: Caddy
Date: Sat, 19 Jul 2025 05:16:43 GMT
Content-Length: 11

root@iv-ydxlc2pz40cva4fg2yxm:~# curl -I http://localhost:18080/admin
curl: (52) Empty reply from server
root@iv-ydxlc2pz40cva4fg2yxm:~# curl -I http://localhost:18080/api
curl: (52) Empty reply from server
  1. 阻止特定User-Agent的请求
example.com {
    @badBots {
        header User-Agent *BadBot*
    }
    abort @badBots
    respond "Welcome to my site!" 200
}
  1. 阻止特定IP地址的访问
example.com {
    @blockedIPs {
        remote_ip 192.168.1.0/24
    }
    abort @blockedIPs
    root * /var/www/html
    file_server
}
  1. 临时关闭站点
example.com {
    abort
}```