nginx 同一个端口支持http和https配置

原理:使用nginx的stream、 stream_ssl_preread模块
由于stream和stream_ssl_preread模块非默认引入,需要在编译安装nginx时引入;编译时添加配置参数 --with-stream --with-stream_ssl_preread_module

1、编译nginx

./configure --prefix=/usr/local/nginx --with-http_ssl_module --with-http_stub_status_module --with-stream --with-stream_ssl_preread_module --with-stream_ssl_module

执行make & make install

2、配置nginx.conf

添加stream配置,让其识别到http访问时默认走http,其余走https

stream {
  upstream  http_gateway {
    server  127.0.0.1:80801;
  }
  upstream  https_gateway {
    server  127.0.0.1:80802;
  }
  map $ssl_preread_protocol $upstream {
    default http_gateway;
    "TLSv1.0" https_gateway;
    "TLSv1.1" https_gateway;
    "TLSv1.2" https_gateway;
    "TLSv1.3" https_gateway;
  }
  
  server {
    listen 8080;
    ssl_preread on;
    proxy_pass $upstream;
  }
  
  upstream http_gateway_8081 {
    server 127.0.0.1:80811;
  }
  upstream https_gateway_4664 {
    server 127.0.0.1:80812;
  }
  map $ssl_preread_protocol $upstream_8081 {
    default http_gateway_8081;
    "TLSv1.0" https_gateway_8081;
    "TLSv1.1" https_gateway_8081;
    "TLSv1.2" https_gateway_8081;
    "TLSv1.3" https_gateway_8081;
  }

  server {
    listen 8081;
    ssl_preread on;
	proxy_pass $upstream_8081;
  }
}

3、简单的nginx.conf示例供参考

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;

    server {
       access_log logs/demo-info.log;
		listen 80801;
		listen 80802 ssl;
		server_name localhost;
		ssl_certificate      /usr/local/nginx/conf/ssl/server.crt;
		ssl_certificate_key  /usr/local/nginx/conf/ssl/server.key;
		ssl_session_cache    shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_protocols  TLSv1.2;  
		ssl_prefer_server_ciphers  on;
		ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
		location / {
            proxy_pass http://127.0.0.1:4399;
        }
    }
	server {
		access_log logs/demo-test.log;
		listen 80811;
		listen 80812 ssl;
		server_name localhost;
		ssl_certificate      /usr/local/nginx/conf/ssl/server.crt;
		ssl_certificate_key  /usr/local/nginx/conf/ssl/server.key;
		ssl_session_cache    shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_protocols  TLSv1.2;  
		ssl_prefer_server_ciphers  on;
		ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;

		location / {
            proxy_pass http://127.0.0.1:4340;
        }
	}

}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值