当前位置:   article > 正文

利用Caddy实现http反向代理_caddy 反向代理

caddy 反向代理

利用Caddy实现http反向代理

1 Caddy是什么

Caddy是一个开源的,使用Golang编写的,支持HTTP/2的Web服务端。它的一个显著特征就是默认启用HTTPS。

nginx类似。

2 多个后端服务

假如现在有3个后端http服务:分别在启动在

app1

http://10.0.0.1:8080

GET /
GET /ping
  • 1
  • 2
  • 3
  • 4

app2

http://10.0.0.2:8080

GET /
GET /ping
  • 1
  • 2
  • 3
  • 4

app3

http://10.0.0.3:8080

GET /
GET /ping
  • 1
  • 2
  • 3
  • 4

3 Caddyfile

localhost {
    # localhost/app1/ping -> http://10.0.0.1:8080/ping
    route /app1/* {
        uri strip_prefix /app1
        reverse_proxy http://10.0.0.1:8080
    }
    route /app2/* {
        uri strip_prefix /app2
        reverse_proxy http://10.0.0.2:8080
    }
    route /app3/* {
        uri strip_prefix /app3
        reverse_proxy http://10.0.0.3:8080
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

Tips

uri strip_prefix /app1的作用是将url中的/app1给去掉然后转发到reverse_proxy上去。

启动caddy

$> caddy run
  • 1

此时使用curl或者浏览器访问

$> curl -v http://localhost/app1/ping
$> curl -v http://localhost/app2/ping
$> curl -v http://localhost/app3/ping
  • 1
  • 2
  • 3

则caddy会分别反向代理到app1、app2、app3上。

4 启用HTTPS

自签证书

本地测试的时候需要安装本地信任机构CA并且自签证书,需要借助mkcert工具

$> brew install mkcert
  • 1

安装CA到本机

$> mkcert -install
  • 1

为主机自签证书

$> mkcert example.org
  • 1

会在当前目录生成example.org.pemexample.org-key.pem这两个文件

配置Hosts

在hosts文件里添加

127.0.0.1 		example.org
  • 1

此时访问example.org就会访问到本机的127.0.0.1

在Caddyfile中添加tls

example.org {
		tls /Users/example.org.pem  /Users/example.org-key.pem
    # example.org/app1/ping -> http://10.0.0.1:8080/ping
    route /app1/* {
        uri strip_prefix /app1
        reverse_proxy http://10.0.0.1:8080
    }
    route /app2/* {
        uri strip_prefix /app2
        reverse_proxy http://10.0.0.2:8080
    }
    route /app3/* {
        uri strip_prefix /app3
        reverse_proxy http://10.0.0.3:8080
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

需要注意的是tls配置的 xx.pemxx-key.pem文件是绝对路径。

重启caddy

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/37692
推荐阅读
相关标签
  

闽ICP备14008679号