部署HAProxy使Shadowsocks与Nginx共用443端口

服务器环境:CentOS7且已安装Shadowsocks与Nginx

安装HAProxy

yum install haproxy -y

配置HAProxy

mv /etc/haproxy/haproxy.cfg /etc/haproxy/haproxy.cfg.bak
vi /etc/haproxy/haproxy.cfg
#输入以下内容
global
  log /dev/log	local0
  log /dev/log	local1 notice
  chroot /var/lib/haproxy
  user haproxy
  group haproxy
  daemon

defaults
  log	global
  mode	tcp
  option  tcplog	
  option	dontlognull
  maxconn  2000
  timeout connect  5000
  timeout client 500000
  timeout server 500000

frontend ssl
  mode tcp
  bind 0.0.0.0:443
  tcp-request inspect-delay 3s
  tcp-request content accept if { req.ssl_hello_type 1 }
  acl www req_ssl_sni -i apad.pro
  acl www req_ssl_sni -i sitename.com
  use_backend nginx if www { req.ssl_hello_type 1 }
  use_backend shadowsocks if !{ req.ssl_hello_type 1 } !{ req.len 0 }

backend nginx
  mode tcp
  server webserver 127.0.0.1:4431

backend shadowsocks
  mode tcp
  server socks 127.0.0.1:8443

其中8443为Shadowsocks使用的端口,将sitename.com更换为Nginx使用的域名

如果Nginx已经运行并正在使用443端口,应修改Nginx配置文件中的Server区域

server {
        listen                      80;
        #listen                     443 ssl http2;
        listen                      1443 ssl http2;
        #省略其它参数#
        proxy_set_header   Host             $host;
        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
        proxy_redirect     off;
        set_real_ip_from 127.0.0.1;
        real_ip_header proxy_protocol;
}

重启Nginx服务后启动HAProxy服务

systemctl restart nginx
systemctl enable haproxy
systemctl start haproxy

此时即可使Shadowsocks与Nginx共用443端口,唯一的不足Shadowsocks无法使用UDP协议,但不太影响一般的科学上网需求。最后别问我为什么要共用443端口 : (