caddy2配置文件配置tp路由

  • Caddyfile 文件

# caddy2配置文件
# 文档 https://caddyserver.com/v2
# 中文文档 https://caddy2.dengxiaolong.com/docs/caddyfile/directives
# 中文文档 https://github.com/phpple/caddy2-cn-doc
# caddy run -config ./Caddyfile
127.0.0.1:8080 {
    root * /home/jcleng/desk/work/www/fastadmin-temp/public/
    # php_fastcgi 的地址
    php_fastcgi 172.19.0.11:8072
    # 用route来解析
    route {
        # 静态文件整个目录是直接(按文件)输出
        file_server /assets/*
        file_server /uploads/*

        # 静态解析网站图标
        file_server /favicon.ico

        # 静态解析 搜索引擎文件
        file_server /robots.txt

        # 先重写前台,再重写后台
        # 前台重写
        @front {
            not file
            path_regexp front (/.+)
        }
        rewrite @front /index.php{uri}
        @admin {
            not file
            path_regexp admin (NaUMFbCdWg\.php)(/.+)
        }
        # 后台重写
        rewrite @admin /NaUMFbCdWg.php{re.admin.2}
    }
}
# dbninja
127.0.0.1:8081 {
    root * /home/jcleng/desk/work/www/dbnanjia/dbninja
    php_fastcgi 172.19.0.11:8072
    file_server
}
  • 私有证书生成

1.CSR文件在线生成工具: https://csr.chinassl.net/generator-csr.html 生成并下载文件 2.自签名免费SSL证书: https://csr.chinassl.net/free-ssl.html 生成并下载证书 3.然后配置

:443 {
  root * /usr/share/caddy
  tls /vagrant_data/www.xxx.com_ssl.crt /vagrant_data/www.xxx.com_key.txt
}
  • 负载均衡和健康检查

# 负载均衡, 健康检查等
# 文档: https://caddy2.dengxiaolong.com/docs/caddyfile/directives/reverse_proxy#health_interval
# 变更配置之后重载配置:
# d:\work\caddy.exe reload -config d:\work\caddy\Caddyfile
:801 {
	reverse_proxy * {
		to http://127.0.0.1:802 http://127.0.0.1:803
		# 负载均衡策略
		# lb_policy ip_hash
		# 检查检查地址/状态/检查间隔时间
		health_uri /health_uri
		health_status 200
		health_interval 500ms
	}
}

:802 {
	root * D:\work\caddy\www\node1
	file_server
}

:803 {
	root * D:\work\caddy\www\node2
	file_server
}

  • 负载监控

# https://github.com/prometheus/prometheus
# 编辑配置:
# prometheus-2.35.0-rc1.windows-amd64\prometheus.yml
# 配置为: targets: ["127.0.0.1:2019"]


# prometheus.yaml 添加job_name部分
global:
  scrape_interval: 15s # default is 1 minute

scrape_configs:
  - job_name: caddy
    static_configs:
      - targets: ['localhost:2019']

# 重启之后查看 caddy (1/1 up)
# http://116.204.106.129:9090/targets
  • 配置2019端口,在caddy文件的第一行加一个对象全局配置即可

{
    admin 0.0.0.0:2019 {

    }
}
  • admin端口2019的api

###获取配置
GET http://116.204.106.129:2019/config/

###修改配置
POST http://116.204.106.129:2019/config/
Content-Type: application/json

{
  "admin": {
    "listen": "0.0.0.0:2019"
  },
  "apps": {
    "http": {
      "servers": {
        "srv0": {
          "listen": [
            ":80"
          ],
          "routes": [
            {
              "handle": [
                {
                  "handler": "reverse_proxy",
                  "upstreams": [
                    {
                      "dial": "192.168.49.2:801"
                    }
                  ]
                }
              ]
            }
          ]
        }
      }
    }
  }
}
  • 代理和跳转

# 代理和跳转
:80 {
	redir https://www.leng2011.icu
}
:443 {
  reverse_proxy * {
    to http://127.0.0.1:31509
  }
  tls /home/jcleng/www.leng2011.icu_bundle.crt /home/jcleng/www.leng2011.icu.key
}

强大的请求验证Request Matchers

  • 灰度请求

# 通过请求匹配,很容易做到灰度请求等
:9898 {
    @canary {
        header Rtype "canary"
    }
    reverse_proxy @canary 127.0.0.1:8081
    reverse_proxy * 127.0.0.1:8080
}



###
GET http://172.17.170.63:9898
token: agent_b47a644dd2ae7b4b0825193520d68f73
Content-Type: application/json
Rtype: canary

  • 请求进行简易验证

# https://caddy2.dengxiaolong.com/docs/caddyfile/matchers#heading


# 用reverse_proxy进行转发,用header进行授权验证,把公网9898端口转发到内网的12346端口,12346禁止公网访问
:9898 {
    @user001 {
        header Authorization "Bearer 65df294084a828ad69b4451b365bed18"
    }
    reverse_proxy @user001 127.0.0.1:12346
}

### 请求
GET http://127.0.0.1:9898/s.php
Authorization: Bearer 65df294084a828ad69b4451b365bed18
  • 例子,组合使用,通过2020端口验证请求到2021端口进行更新Caddyfile配置文件并重新加载

:2020 {
    @useradmin {
        header Authorization "Bearer 65df294084a828ad69b4451b365bed18"
    }
    reverse_proxy @useradmin 127.0.0.1:2019 {
      # 请求头修改为localhost:2019
      header_up Host localhost:2019
      header_up X-Real-IP {remote}
      header_up X-Forwarded-For {remote}
      header_up X-Forwarded-Port {server_port}
      header_up X-Forwarded-Proto "http"
   }
}


### 上传文件
POST http://localhost:2020/load
Authorization: Bearer 65df294084a828ad69b4451b365bed18
Content-Type: text/caddyfile

< /home/jcleng/work/agent/.vscode/Caddyfile


systemd.services."caddy" = {
  description = "Caddy";
  documentation = [ "https://caddyserver.com/docs/" ];
  wantedBy = [ "multi-user.target" ];
  after = [ "network.target" "network-online.target" ];
  requires = [ "network-online.target" ];
  serviceConfig = {
    Type = "notify";
    ExecStart = "/run/current-system/sw/bin/caddy run --environ --config /home/jcleng/test_hold/Caddyfile";
    ExecReload = "/run/current-system/sw/bin/caddy reload --config /home/jcleng/test_hold/Caddyfile --force";
    TimeoutStopSec = "5s";
    LimitNOFILE = 1048576;
    LimitNPROC = 512;
    PrivateTmp = true;
    ProtectSystem = "full";
    AmbientCapabilities = "CAP_NET_BIND_SERVICE";
  };
};
systemd.services.caddy.enable = true;
  • 平滑重启更新配置文件

./caddy_linux_amd64 reload --config ./Caddyfile
  • 实时状态

### 获取实时状态
GET http://127.0.0.1:2019/metrics
  • caddy注册服务

docker cp ./caddy systemdos:/usr/local/bin/

# 最简单的进测试
mkdir -p /etc/caddy/
vim /etc/caddy/Caddyfile

:12345 {
    root * /usr/local/bin
    file_server
}


vim /etc/systemd/system/caddy.service

[Unit]
Description=Caddy web server
Documentation=https://caddyserver.com/docs/
After=network.target

[Service]
Environment=CADDY_HOME=/var/lib/caddy
Environment=CADDY_CONFIG=/etc/caddy/Caddyfile
Environment=CADDY_VERSION=last
ExecStart=/usr/local/bin/caddy run --config /etc/caddy/Caddyfile --resume
ExecReload=/usr/local/bin/caddy reload --config /etc/caddy/Caddyfile --force
Restart=on-failure
LimitNOFILE=1048576

[Install]
WantedBy=multi-user.target

# 重载
systemctl daemon-reload
systemctl start caddy
# 重载
systemctl reload caddy
systemctl enable caddy

# 查看服务日志(最新在最后页)
journalctl -u caddy.service -b
  • 使用api请求json

### json文档: https://caddy2.dengxiaolong.com/docs/json/
curl http://localhost:2019/load \
	-H "Content-Type: application/json" \
	-d @/home/jcleng/work/temp/init.json
  • 支持灰度

Caddyfile

{
    admin 0.0.0.0:2019 {

    }
}

init.json

{
    "apps": {
        "http": {
            "servers": {
                "mysite": {
                    "listen": [
                        ":2015"
                    ],
                    "routes": [
                        {
                            "handle": [
                                {
                                    "handler": "reverse_proxy",
                                    "upstreams": [
                                        {
                                            "dial": "127.0.0.1:8081"
                                        }
                                    ]
                                }
                            ],
                            "match": [
                                {
                                    "header": {
                                        "Rtype": [
                                            "canary"
                                        ]
                                    }
                                }
                            ]
                        },
                        {
                            "handle": [
                                {
                                    "handler": "static_response",
                                    "body": "Hello, world!"
                                }
                            ]
                        }
                    ]
                }
            }
        }
    }
}