你可能会碰到这个程序要用443端口,那个程序也要使用443的情况。这时候就要用到nginx的stream进行分流了。

假设有web1,web2两个都要用到443端口。则配置方法如下:

nginx.conf 配置文件

nginx的末尾加上下面代码即可。

stream {
    map $ssl_preread_server_name $upstream {
        web1.moeelf.com web1;
        web2.moeelf.com web2;
        default web;
    }

    log_format stream '$remote_addr [$time_local] [$ssl_preread_server_name] [$upstream] $status $bytes_sent $bytes_received $session_time';
    access_log /var/log/nginx/stream.log stream;

    upstream web1 {
        server web1:65531;
    }
    upstream web2 {
        server web2:65532;
    }
    upstream web {
        server nginx:4433;
    }
    server {
        listen 443 reuseport;
        listen [::]:443 reuseport;
        proxy_pass $upstream;
        ssl_preread on;
    }
}

虚拟主机配置文件

将下面代码保存为sni.conf文件,放到虚拟主机目录。nginx安装方式不一样,放的位置会不一样。一般位于 /etc/nginx/conf.d/ 或 /usr/local/nginx/conf/vhost/ 下面。

server {
    listen 65531 ssl http2 reuseport;
    server_name web1.moeelf.com;

    ssl_certificate       /etc/nginx/ssl/web1.moeelf.com/fullchain.cer;
    ssl_certificate_key   /etc/nginx/ssl/web1.moeelf.com/web1.moeelf.com.key;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
    ssl_prefer_server_ciphers on;

    #log_format stream '$remote_addr [$time_local] [$ssl_preread_server_name] [$route] $status $bytes_sent $bytes_received $session_time';
    access_log /var/log/nginx/web1.moeelf.com.log;
}
server {
    listen 65532 ssl http2 reuseport;
    server_name web2.moeelf.com;

    ssl_certificate       /etc/nginx/ssl/web2.moeelf.com/fullchain.cer;
    ssl_certificate_key   /etc/nginx/ssl/web2.moeelf.com/web2.moeelf.com.key;
    ssl_protocols TLSv1.1 TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE:ECDH:AES:HIGH:!NULL:!aNULL:!MD5:!ADH:!RC4:!DH:!DHE;
    ssl_prefer_server_ciphers on;

    #log_format stream '$remote_addr [$time_local] [$ssl_preread_server_name] [$route] $status $bytes_sent $bytes_received $session_time';
    access_log /var/log/nginx/web2.moeelf.com.log;
}