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

原理:使用nginx的stream、 stream_ssl_preread模块

1.编译nginx

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

./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:8077;
  }
  upstream https_gateway {
    server  127.0.0.1:8076;
  }
  map $ssl_preread_protocol $upstreama{
    default http_gateway;
    "TLSv1.0" https_gateway;
    "TLSv1.1" https_gateway;
    "TLSv1.2" https_gateway;
    "TLSv1.3" https_gateway;
  }

  server {
    listen 2345;
    ssl_preread on;
    proxy_pass $upstreama;
  }
}

http {
******
}

3.配置http和https访问资源

复制代码
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
     upstream gateway_service{
          server  127.0.0.1:8077  weight=1;
          server  127.0.0.1:8076  weight=2;
     }

    server {
        listen       8077;
        listen       8076 ssl;
        server_name  192.168.19.1;
        ssl_certificate /root/Public/ssl/cert.pem;
    ssl_certificate_key /root/Public/ssl/key.pem;
    ssl_prefer_server_ciphers  on;
    ssl_session_cache shared:SSL:1m;
    ssl_session_timeout 5m;
    client_max_body_size 100M;
        #ssl_certificate      xxx.pem;
       # ssl_certificate_key  xxx.key;
        location / {
            proxy_pass http://gateway_service;
        }
    }

}

重启ng,即可同时通过http和https访问了。

相关推荐
Benszen5 小时前
Harbor镜像仓库部署与HTTPS配置
网络协议·http·https
Augustvic5 小时前
gRPC基本原理
后端·http·中间件·rpc
senijusene5 小时前
用C语言制作一个简易HTTP服务器:实现手机商城用户认证与搜索
服务器·c语言·http
枕布响丸辣8 小时前
Web 技术基础与 Nginx 网站环境部署超详细教程
运维·前端·nginx
程序员果子8 小时前
Nginx 从入门到精通:全面解析与实战指南
linux·运维·服务器·nginx
_下雨天.10 小时前
Nginx核心功能学习
运维·学习·nginx
gameboy03110 小时前
在Nginx上配置并开启WebDAV服务的完整指南
java·运维·nginx
白太岁10 小时前
通信:(10) 应用层(第5层):http 与 https
网络协议·http·https
zuoerjinshu12 小时前
Nginx实现接口复制
运维·nginx·junit
陈皮糖..12 小时前
Ansible实战教程----使用Ansible角色源码编译部署nginx服务
linux·运维·nginx·自动化·云计算·ansible