------------ ------------ # 一、起因 我儿需要 # 二、发现问题 在Nginx反向代理的配置过程中,发现如果不开启ssl配置,那么浏览器访问,连接直接被重置,如果开启ssl,那么需要证书。那么说明,nginx默认的https配置块无法支持7层的https转发,因为浏览器发出的握手协议是和Nginx进行的,此时Nginx并没有开启ssl,所以报错。 # 三、SNI侦测 SNI(Server Name Indication)是为了解决一个服务器使用多个域名和证书的SSL/TLS扩展。一句话简述它的工作原理就是,在连接到服务器建立SSL链接之前先发送要访问站点的域名(Hostname),这样服务器根据这个域名返回一个合适的证书。目前,大多数操作系统和浏览器都已经很好地支持SNI扩展,OpenSSL 0.9.8已经内置这一功能,新版的nginx也支持SNI。 # 四、Nginx的SNI 默认,新版的Nginx已经支持SNI,所以一个nginx下可以代理多个不同的域名。但是那是基于ssl配置在nginx下。如果让nginx代理内部的https,此法不行。 # 五、Nginx的Stream 不知道从何时开始,Nginx也支持了TCP转发,也就是OSI中的第四层转发。SSL是依靠TCP传输,那么只需要把TCP上层的数据剥离出来,封装后转发给代理的443端口,然后将代理服务器的返回数据剥离出来,在通过公网ip返回,那么就相当于浏览器在直接和内网的443端口通信。 # 六、Nginx的ssl_preread 不知道又从何开始,Nginx支持了ssl的preread,允许提取所述信息的ClientHello而不终止SSL / TLS。例如,服务器名称通过请求的消息SNI。该模块不是默认生成的,它应该使用--with-stream_ssl_preread_module配置参数启用。需要安装Nginx时加载下stream_ssl_preread_module模块。 # 七、安装nginx和所需的module ```shell #安装编译依赖 yum install -y gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel wget https://nginx.org/download/nginx-1.18.0.tar.gz tar zxvf nginx-1.18.0.tar.gz cd nginx-1.18.0 #添加https转发需要的module ./configure --prefix=/usr/local/nginx --with-stream --with-stream_ssl_preread_module --with-stream_ssl_module make && make install ``` # 八、配置 备份 ```shell cp /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/nginx.conf-bak ``` 修改config ```shell vim /usr/local/nginx/conf/nginx.conf ``` ```shell worker_processes 1; events { worker_connections 1024; } pid /var/run/nginx.pid; stream { log_format proxy '$proxy_protocol_addr $remote_addr [$time_local] ' '$protocol $status $bytes_sent $bytes_received ' '$session_time "$upstream_addr" ' '"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"'; access_log /usr/local/nginx/logs/access.log proxy; error_log /usr/local/nginx/logs/error.log info; map_hash_bucket_size 64; map $ssl_preread_server_name $backend_pool { www.xiaoleizhang.com test; default server_test; } upstream test{ server 10.60.60.16:443; } server{ listen 443; ssl_preread on; proxy_pass $backend_pool; proxy_connect_timeout 15s; proxy_timeout 15s; proxy_next_upstream_timeout 15s; } } ``` 配置链接参考 https://cloud.tencent.com/developer/section/1259623 https://cloud.tencent.com/developer/section/1259675 验证配置 ```shell /usr/local/nginx/sbin/nginx -t ``` 启动 ```shell /usr/local/nginx/sbin/nginx /usr/local/nginx/sbin/nginx -s stop #关闭服务 ``` 测试访问 https://www.xiaoleizhang.com 是可以的 最后修改:2022 年 03 月 01 日 © 允许规范转载 赞 1 如果觉得我的文章对你有用,请随意赞赏