泽兴芝士网

一站式 IT 编程学习资源平台

如何使用caddy在一个端口上反向代理http/https/ssh?

caddy具有强大的layer4协议路由转发能力,当前版本已支持的协议:

配置语法见:

Module layer4 - Caddy Documentation



最新支持协议见:

github.com

当前已经支持:

http/openvpn/postgres/haproxy/quic/socket4-5/ssh/tls/winbox/wireguard/xmpp

一些云主机由于等保安全问题,往往会限制外网端口暴露数量,为了在80或443端口同时承载http,https,ssh,可使用caddy如下配置:

{
	# Global options
	admin off
	auto_https off
	ocsp_stapling off
	log {
		level INFO
		output file myhost.log
	}

	# Layer 4 server configuration
	layer4 {
		0.0.0.0:8000 {
			# HTTP proxy 
			@insecure http
			route @insecure {
				proxy localhost:80
			}
			# TLS proxy 
			@secure tls 
			route @secure {
				proxy 127.0.0.1:443
			}

			# SSH proxy
			@ssh ssh
			route @ssh {
				proxy localhost:22
			}
			# others ignore
			route {
				echo
			}
		}
	}
}

# HTTP server configuration
:443 {
	# File server configuration
	root * www
	file_server {
		index index.html index.htm 
	}

	# TLS configuration
	tls my-cert.pem my-key.pem
}

:80 {
	# File server configuration
	root * www
	file_server

	reverse_proxy /rpcp localhost:29001 
	reverse_proxy /rpcs localhost:29001 
}

此配置演示了使用caddy在唯一一个端口8000上,同时承载了http/https/ssh流量;并且通过websocket承载grpc流量(或者其他任何支持web socket的RPC框架)。直接可以运行使用:

caddy run -c Caddyfile
2025/05/11 06:48:32.648 INFO    maxprocs: Leaving GOMAXPROCS=8: CPU quota undefined
2025/05/11 06:48:32.650 INFO    GOMEMLIMIT is updated   {"package": "github.com/KimMachineGun/automemlimit/memlimit", "GOMEMLIMIT": 15196749004, "previous": 9223372036854775807}
2025/05/11 06:48:32.651 INFO    using config from file  {"file": "Caddyfile"}
2025/05/11 06:48:32.655 INFO    adapted config to JSON  {"adapter": "caddyfile"}
2025/05/11 06:48:32.655 WARN    Caddyfile input is not formatted; run 'caddy fmt --overwrite' to fix inconsistencies   {"adapter": "caddyfile", "file": "Caddyfile", "line": 43}
2025/05/11 06:48:32.655 INFO    redirected default logger       {"from": "stderr", "to": "myhost.log"}
2025/05/11 06:48:32.685 INFO    serving initial configuration
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言