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

相关推荐
bearpping4 小时前
Nginx 配置:alias 和 root 的区别
前端·javascript·nginx
肠胃炎11 小时前
挂载方式部署项目
服务器·前端·nginx
曲幽14 小时前
FastAPI实战:WebSocket vs Socket.IO,这回真给我整明白了!
python·websocket·nginx·socket·fastapi·web·async·socketio
袁庭新17 小时前
M系列芯片Mac上通过Homebrew一键安装/卸载Nginx并上线项目全指南
运维·nginx·macos·袁庭新·袁庭新ai
huohaiyu17 小时前
HTTPS的加密流程
网络协议·http·https
德迅云安全杨德俊18 小时前
直面 DDoS 威胁:从现状到解决方案
网络·安全·web安全·https·ddos
Densen201418 小时前
发布blazor应用到Linux, 使用nginx作为WebSocket代理
linux·websocket·nginx
不是书本的小明18 小时前
Apache vs Nginx vs Tomcat 核心区别与优化
nginx·tomcat·apache
Barkamin19 小时前
HTTPS的工作过程
网络协议·http·https
cccyi719 小时前
支持 HTTP 协议的主从 Reactor 高性能服务器组件
服务器·http·reactor