HAProxy https实现
1.证书制作:
[root@centos7 ~]mkdir /etc/haproxy/certs/ [root@centos7 ~]cd /etc/haproxy/certs/ [root@centos7 certs]#openssl genrsa -out haproxy.key 2048 [root@centos7 certs]#openssl req -new -x509 -key haproxy.key -out haproxy.crt -subj "/CN=www.magedu.org" #或者用下一条命令实现 [root@centos7 certs]#openssl req -x509 -newkey rsa:2048 -subj "/CN=www.magedu.org" -keyout haproxy.key -nodes -days 365 -out haproxy.crt [root@centos7 certs]#cat haproxy.key haproxy.crt > haproxy.pem #crt 后证书文件为PEM格式,且同时包含证书和所有私钥 [root@centos7 certs]#openssl x509 -in haproxy.pem -noout -text #查看证书
2.https配置
frontend magedu_http_port
bind 10.0.0.7:80
bind 10.0.0.7:443 ssl crt /etc/haproxy/certs/haproxy.pem #配置HAProxy支持https协议,支持ssl会话
redirect scheme https if !{ ssl_fc } #注意{ }内的空格 #把80端口的请求重向定443
#redirect scheme https if !{ ssl_fc } #理解说明:客户端是https协议端口来时ssl_fc为真取反成假,不执行,反之http来的ssl_fc为假取反成真,执行重写向。
http-request set-header X-forwarded-Port %[dst_port] #向后端传递用户请求的协议和端口(frontend或backend)
http-request add-header X-forwarded-Proto https if { ssl_fc } 传递http协议给后端。
mode http
balance roundrobin
log global
option httplog
backend pc_hosts
mode http
#http-request set-header X-forwarded-Port %[dst_port] 也可加在此处,
#http-request add-header X-forwarded-Proto https if { ssl_fc }
server web2 10.0.0.27:80 check inter 2000 fall 3 rise 5
另一种方法
#web server http
frontend web_server-http
bind 192.168.7.101:80
redirect scheme https if !{ ssl_fc }
mode http
use_backend web_host
#web server https
frontend web_server-https
bind 192.168.7.101:443 ssl crt /usr/local/haproxy/certs/haproxy.pem
mode http
use_backend web_host
3.日志格式修改
修改后端服务器的日志格式
[root@centos27 ~]#vim /etc/httpd/conf/httpd.conf
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" \"%{X-Forwarded-Port}i\" \"%{X-Forwarded-Proto}i\"" combined
修改后端nginx服务器的日志格式测试失败
#查看后端服务器的访问日志
[root@centos27 ~]#tail /var/log/httpd/access_log
10.0.0.7 - - [04/Apr/2020:10:40:17 +0800] "HEAD / HTTP/1.1" 200 - "-" "curl/7.19.7 (x86_64-redhat-linux-gnu) libcurlS/3.27.1 zlib/1.2.3 libidn/1.18 libssh2/1.4.2" "443" "https"
4.验证https #-L 参数会让 HTTP 请求跟随服务器的重定向,curl默认是不重定向。-k 许忽略证书进行 SSL 连接
[root@localhost7e ~]# curl -Ik http://www.magedu.org #curl默认是不重定向 HTTP/1.1 302 Found content-length: 0 location: https://www.magedu.org/ cache-control: no-cache [root@localhost7e ~]# curl -IkL http://www.magedu.org HTTP/1.1 302 Found content-length: 0 location: https://www.magedu.org/ cache-control: no-cache HTTP/1.1 200 OK server: nginx/1.20.1 date: Wed, 27 Jul 2022 06:30:29 GMT content-type: text/html content-length: 15 last-modified: Wed, 27 Jul 2022 06:29:53 GMT etag: "62e0db61-f" accept-ranges: bytes


浙公网安备 33010602011771号