本文记录Caddy2从安装到配置h2c反代的全部过程
环境: ubuntu 18.04, Caddy v2.4.5
Caddy2 v2.1.0之后才支持h2c
安装
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo tee /etc/apt/trusted.gpg.d/caddy-stable.asc
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
Caddyfile
Caddyfile 地址
/etc/caddy/Caddyfile
Caddyfile 全文
domain
# Set this path to your site's directory.
#root * /usr/share/caddy
root * /var/www/html
# Enable the static file server.
file_server
# Another common task is to set up a reverse proxy:
# reverse_proxy localhost:8080
# Or serve a PHP site through php-fpm:
#php_fastcgi unix//run/php/php7.4-fpm.sock
#encode gzip
# Refer to the Caddy docs for more information:
# https://caddyserver.com/docs/caddyfile
tls {
dns cloudflare <cloudflare_api_here>
}
# 如使用自己的ssl证书,则参照下面一行:
# tls /path/to/certificate /path/to/privkey
@websocket {
path /wspath
header Connection *Upgrade*
header Upgrade websocket
}
reverse_proxy @websocket localhost:wsport
reverse_proxy /h2path http://localhost:h2port {
#header_up Host {http.request.host}
#header_up X-Real-IP {http.request.remote.host}
#header_up X-Forwarded-For {http.request.remote.host}
#header_up X-Forwarded-Port {http.request.port}
#header_up X-Forwarded-Proto {http.request.scheme}
transport http {
#tls
#tls_insecure_skip_verify
versions h2c 2
}
}
一些解释
@websocket 是一个匹配器。凡是匹配到 /wspath 路径的,符合WebSocket协议的请求,都会被代理到localhost的wsport上。
同样,访问到 /h2path 路径的请求会被反向代理到localhost的wsport协议。这里不用匹配器是因为写出来就一行: @h2path{ path /h2path},没必要搞得太复杂。
Cloudflare 不支持与源服务器进行 h2 通信,套 Cloudflare (或者说大多数cdn) 则无法成功转发h2流量。