ssh、http共用一个端口

nginx-1.15.2 版本新增了$ssl_preread_protocol 变量,通过该变量可以使用 stream 反向代理时预先判断连接是否为SSL/TLS协议或者为非SSL/TLS协议,从而实现同一个端口来转发不同的业务。

nginx配置

https://www.php.cn/nginx/422091.html

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;
    }
}

http、https复用端口,也差不多,参见https://www.zhihu.com/question/34017892/answer/1544258221