nginx-1.15.2 版本新增了$ssl_preread_protocol 变量,通过该变量可以使用 stream 反向代理时预先判断连接是否为ssl/tls协议或者为非ssl/tls协议,从而实现同一个端口来转发不同的业务。
stream_ssl_preread模块检查初始clienthello在ssl或tls连接消息,并且提取其可用于管理连接几个值。$ssl_preread_protocol版本1.15.2中添加的变量从消息client_version字段中捕获最新的ssl / tls版本号clienthello。如果消息中supported_versions存在扩展名clienthello,则变量设置为tlsv1.2/tlsv1.3。
实例:在一台反向代理服务器上运行nginx,并监听443端口,后端有两组服务,一个为https(开启tls1.2/1.3)网站服务,另一个为ssh 服务,我们要实现这两组服务运行在同一个端口上(配置的443端口)--入口请求由nginx自动区分。
为简便,我这时直接使用 docker环境
nginx 版本
# docker exec -it nginx nginx -vnginx version: nginx/1.15.10built by gcc 8.2.0 (alpine 8.2.0)built with openssl 1.1.1b 26 feb 2019...<省略若干行>...
目录文件
# tree ./nginx-with-l4-reuse/./nginx-with-l4-reuse/├── config│ └── nginx│ ├── conf.d│ │ └── default.conf│ ├── fastcgi.conf│ ├── fastcgi_params│ ├── mime.types│ └── nginx.conf└── docker-compose.yaml3 directories, 6 files
docker-compose.yaml
# docker-compose.yamlversion: 2.4services: nginx: container_name: nginx image: nginx:alpine network_mode: host volumes: - ./config/nginx:/etc/nginx/:ro ports: - 443:443 restart: always
nginx.conf
user nginx;worker_processes 2;error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;events { worker_connections 1024;}stream { log_format stream '{@access_time:$time_iso8601,' 'clientip:$remote_addr,' 'pid:$pid,' 'pro:$protocol,' 'ssl_pro: $ssl_preread_protocol', 'pro:$protocol,' 'stus:$status,' 'sent:$bytes_sent,' 'recv:$bytes_received,' 'sess_time:$session_time,' 'up_addr:$upstream_addr,' 'up_sent:$upstream_bytes_sent,' 'up_recv:$upstream_bytes_received,' 'up_conn_time:$upstream_connect_time,' 'up_resp_time:$upstream_first_byte_time,' 'up_sess_time:$upstream_session_time}'; upstream ssh { server 192.168.50.212:22; } upstream web { server 192.168.50.215:443; } map $ssl_preread_protocol $upstream { default ssh; tlsv1.2 web; tlsv1.3 web; } # ssh and ssl on the same port server { listen 443; proxy_pass $upstream; ssl_preread on; access_log /var/log/nginx/stream_443.log stream; }}
$ssl_preread_protocol 实现ip层实现了不同业务配置,在某种需求上很有意义--虽然存在功能限制。然而tengine-2.3.0已经实现的ip层基于域名转发,或许这一特性会引入到nginx。
更多nginx相关技术文章,请访问nginx使用教程栏目进行学习!
以上就是nginx如何端口复用的详细内容。