前言

阿里云快到期了,这几天在手动迁移应用,然后遇到了很蛋疼的事,我的域名设置了HSTS,只允许HTTPS请求,不允许HTTP请求。以前懒的搞,一直是用IP访问的,趁着这次机会,就打算弄个反代,让它支持HTTPS。考虑到服务器性能捉急,这次就不装宝塔面板了,手动装个Caddy完事,图新鲜装了个Caddy V2,中文文档不太多,遇到了不少坑,就写个简单的指南吧。

附上链接:Caddy英文文档

安装Caddy

引用自官方文档

  • Debian/Ubuntu

    sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo apt-key add -
    curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee -a /etc/apt/sources.list.d/caddy-stable.list
    sudo apt update
    sudo apt install caddy
  • CentOS/RedHat

    dnf install 'dnf-command(copr)'
    dnf copr enable @caddy/caddy
    dnf install caddy

常用命令

# 启动
systemctl start caddy
# 停止
systemctl stop caddy
# 重启
systecmtl restart caddy
# 开机自启
systemctl enable caddy
# 取消开机自启
systemctl disable caddy

配置文件

默认配置

Caddy默认的配置文件为/etc/caddy/Caddyfile,默认配置如下:

# The Caddyfile is an easy way to configure your Caddy web server.
#
# Unless the file starts with a global options block, the first
# uncommented line is always the address of your site.
#
# To use your own domain name (with automatic HTTPS), first make
# sure your domain's A/AAAA DNS records are properly pointed to
# this machine's public IP, then replace the line below with your
# domain name.
: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
#
# Or serve a PHP site through php-fpm:
# php_fastcgi localhost:9000
#
# Refer to the Caddy docs for more information:
# https://caddyserver.com/docs/caddyfile
  • :80定义了一个站点,监听来自80端口的所有请求

  • root * /usr/share/caddy定义了站点根目录

  • file_server表示静态文件服务器,允许访问站点根目录下的文件

设置反向代理

配置文件:

{
  experimental_http3
}
http://xxx.chrxw.com{
    encode gzip
    reverse_proxy http://localhost:8000
}

配置文件修改以后,使用命令systemctl restart caddy即可重启caddy,因为我的域名使用了HSTS,所以还是不能访问,还得配置TLS

配置文件分为两个部分,第一部分是全局配置,第二个是站点配置

  • experimental_http3表示启用QUIC支持,没啥用,纯好玩

  • encode gzip表示对响应启用Gzip压缩

  • reverse_proxy http://localhost:8000表示反代本地的8000端口

配置TLS证书

首先得有TLS证书,我放在/home/.caddy/目录下,权限设置:

# 修改文件属组
chown caddy:caddy /home/.caddy -R
# 去除其他用户的读写权限
chmod go-rwx /home/.caddy -R

配置文件修改成这样:

{
  experimental_http3
}
https://xxx.chrxw.com{
    encode gzip
    tls /home/.caddy/xxx_chrxw_com.pem /home/.caddy/xxx_chrxw_com.key
    reverse_proxy http://localhost:8000
}

配置文件修改以后,使用命令systemctl restart caddy即可重启caddy,如果一切顺利,已经支持HTTPS访问了。
如果还是访问不了,使用命令systemctl status caddy -l查看错误原因。

配置文件只是增加了TLS证书,然后把站点的访问协议改成了https

最后修改:2021 年 04 月 02 日 01 : 46 PM