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

相关推荐
conkl5 分钟前
构建健壮的前端请求体系:从 HTTP 状态码到 Axios 实战
前端·网络协议·http
梁正雄2 小时前
linux服务-nginx原理与安装-1
linux·运维·nginx
java_logo4 小时前
BUSYBOX Docker 容器化部署指南
java·运维·python·nginx·docker·容器·运维开发
e***74955 小时前
Nginx 常用安全头
运维·nginx·安全
q***23927 小时前
nginx简单命令启动,关闭等
java·服务器·nginx
ttthe_MOon7 小时前
Nginx实战:状态码、反向代理原理与负载均衡实战详解
运维·nginx·负载均衡
v***43178 小时前
Nginx WebSocket 长连接及数据容量配置
运维·websocket·nginx
IUGEI8 小时前
Websocket、HTTP/2、HTTP/3原理解析
java·网络·后端·websocket·网络协议·http·https
归叶再无青8 小时前
nginx从入门到实践全指南
运维·nginx·bash
n***26569 小时前
Nginx反向代理出现502 Bad Gateway问题的解决方案
运维·nginx·gateway