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

相关推荐
C_心欲无痕5 小时前
nginx - 实现域名跳转的几种方式
运维·前端·nginx
掘根8 小时前
【仿Muduo库项目】HTTP模块3——HttpContext子模块
网络·网络协议·http
瓦尔登湖懒羊羊8 小时前
到底能不能把HTTP1.0讲明白了
http
令狐少侠20118 小时前
docker基本操作 部署启动nginx
nginx·docker·容器
知南x9 小时前
【物联网视频监控系统----韦东山老师视频总结】(4)流媒体方案的实现之Nginx
物联网·nginx·音视频
不穿格子的程序员11 小时前
计算机网络篇1:OSI + HTTP进化史 + 三次握手四次挥手
网络协议·计算机网络·http
成为你的宁宁14 小时前
【Zabbix运维监控实战(附图文教程):Nginx 服务可用性、连接请求状态、CPU 内存占用与 JVM(Jar 包 / Tomcat)全维度监控】
运维·jvm·nginx·zabbix
特行独立的猫15 小时前
python+Proxifier+mitmproxy实现监听本地网路所有的http请求
开发语言·爬虫·python·http
CCPC不拿奖不改名15 小时前
基于FastAPI的API开发(爬虫的工作原理):从设计到部署详解+面试习题
爬虫·python·网络协议·tcp/ip·http·postman·fastapi
掘根15 小时前
【仿Muduo库项目】HTTP模块4——HttpServer子模块
网络协议·http·php