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

相关推荐
winlife_8 小时前
在 Unity Editor 里跑 HTTP MCP server:主线程边界与请求 marshal 的实现要点
http·unity·游戏引擎·多线程·mcp
游戏开发爱好者811 小时前
使用Fiddler设置HTTPS抓包诊断Power Query网络问题
android·ios·小程序·https·uni-app·iphone·webview
加号311 小时前
【Python】 实现 HTTP 网络请求功能入门指南
网络·python·http
相思难忘成疾13 小时前
Nginx 子目录多站点配置实验(HTTP/HTTPS 分离部署)
linux·运维·nginx·http·https·vim
JiaWen技术圈16 小时前
HTTP/3 协议基础
网络·网络协议·http
閞杺哋笨小孩1 天前
面向「机构按域名访问、同一套前端」的 Nginx 示例
nginx
源远流长jerry1 天前
Linux 本机网络通信机制深度解析:Loopback 设备原理
linux·运维·服务器·网络·tcp/ip·nginx·负载均衡
落叶_Jim1 天前
Let‘s Encrypt证书有效期缩短至90天后,如何实现自动续期
网络协议·https·ssl
Shingmc32 天前
【Linux】应用层协议HTTP
网络·网络协议·http
spmcor2 天前
一文搞定 Nginx 开机自启:Windows / Linux / macOS 全平台指南
nginx