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访问了。

相关推荐
米丘7 小时前
Connect 深度解析:Node.js 中间件框架的基石
javascript·http·node.js
csdn_aspnet10 小时前
在 ASP.NET Core 中使用自定义属性实现 HTTP 请求和响应加密
http·asp.net·.netcore
不知名。。。。。。。。12 小时前
HTTP协议
网络·网络协议·http
冉佳驹12 小时前
Qt【第六篇】 ——— 事件处理、多线程、网络与文件等操作详解
qt·http·udp·tcp·事件·多线程与互斥锁
chxii13 小时前
linux 下用 acme.sh 搞定 Nginx 免费 SSL 证书自动续期(上)
nginx
大阿明14 小时前
使用vite打包并部署vue项目到nginx
前端·vue.js·nginx
一条闲鱼_mytube14 小时前
【深入理解】HTTP/3 与 QUIC 协议:从原理到 Go 语言实战
网络协议·http·golang
wzb5614 小时前
把 Vim 打造成 Nginx 开发 / 调试 IDE(WSL Ubuntu 完整教程)
linux·ide·nginx·ubuntu·vim·c/c++
EmbeddedCore15 小时前
物联网通讯协议怎么选?MQTT、TCP、UDP、HTTP、HTTPS全面解析
物联网·tcp/ip·http
FreeBuf_15 小时前
Nginx-UI 备份恢复漏洞 PoC 公开:攻击者可篡改加密备份并注入恶意配置
运维·nginx·ui