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

相关推荐
siger14 小时前
前端部署缓存策略实践
前端·nginx
曲幽17 小时前
FastAPI子应用挂载:别再让root_path坑你一夜
python·nginx·fastapi·web·mount·admin·404·docs·root_path
努力的lpp19 小时前
小迪安全第10天:HTTP数据包分析与构造
网络协议·安全·http
带娃的IT创业者20 小时前
WeClaw_41_桌面端与PWA文件双向传输:WebSocket与HTTP混合协议设计
websocket·网络协议·http·文件传输·pwa
yashuk21 小时前
Ubuntu 系统下安装 Nginx
数据库·nginx·ubuntu
桌面运维家1 天前
Nginx服务器安全:高级访问控制与流量清洗实战
服务器·nginx·安全
yhole1 天前
Nginx解决前端跨域问题
运维·前端·nginx
问道飞鱼1 天前
【服务器知识】nginx安全架构巡检
服务器·nginx·安全架构
左手厨刀右手茼蒿1 天前
Flutter 组件 http_requests 适配鸿蒙 HarmonyOS 实战:极简网络请求,构建边缘端轻量级 RESTful 通讯架构
网络·flutter·http
斌味代码2 天前
Nginx 配置实战(2026最新版):反向代理+负载均衡+HTTPS+性能优化一网打尽
nginx·https·负载均衡