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

相关推荐
Gazer_S14 分钟前
【HTTP通信:生活中的邮局之旅】
网络协议·http·生活
layman05282 小时前
node.js 实战——(Http 知识点学习)
http·node.js
Gazer_S3 小时前
【HTTP/2:信息高速公路的革命】
网络·网络协议·http
lLinkl3 小时前
项目笔记2:post请求是什么,还有什么请求
服务器·网络协议·http
花千树-0105 小时前
使用 Frp 同时实现 HTTP 和 HTTPS 内网穿透
网络协议·http·https
夜空晚星灿烂5 小时前
http通信之axios vs fecth该如何选择?
网络·网络协议·http
爱的叹息5 小时前
【前端】基于 Promise 的 HTTP 客户端工具Axios 详解
前端·网络·网络协议·http
Sonetto19996 小时前
Nginx 反向代理,啥是“反向代理“啊,为啥叫“反向“代理?而不叫“正向”代理?它能干哈?
运维·前端·nginx
zheshiyangyang19 小时前
HTTP相关
网络·网络协议·http
我的golang之路果然有问题20 小时前
快速上手GO的net/http包,个人学习笔记
笔记·后端·学习·http·golang·go·net