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

相关推荐
CodexDave9 小时前
MySQL事务隔离级别与MVCC机制解析
前端·数据库·mysql·nginx·性能优化·负载均衡
猫头_17 小时前
AI 流式传输工程指南:有了 EventSource 为何还要 Fetch?
javascript·http·llm
Chloeis Syntax17 小时前
JAVAEE初阶 --- 构造HTTP请求
网络·网络协议·http·postman
chexus21 小时前
20. 深入 Nginx 信号处理
linux·c语言·网络·nginx
触底反弹1 天前
前后端通信不是魔法,是 HTTP 协议、数据格式和浏览器安全机制共同演奏的交响曲
http·https·浏览器
名字还没想好☜2 天前
Nginx 反向代理与负载均衡配置实战
运维·nginx·负载均衡
逑之2 天前
HTTP、HTTPS2
网络·网络协议·http
YYYing.2 天前
【C++大型项目之高性能服务器框架 (九) 】协议抽象与Http服务器模块
服务器·c++·http·高性能·c/c++·后端框架
_waylau2 天前
Spring Framework HTTP服务客户端详解
java·后端·网络协议·spring·http·spring cloud
Android-Flutter2 天前
Android的http和https知识点
android·http·https