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

相关推荐
是个西兰花1 小时前
http讲解
网络·网络协议·http
Lsetea2 小时前
OpenSSL报certificate revoked:error 23与CRL吊销层级排查
linux·https·ssl证书·openssl·crl
HelloWorld工程师3 小时前
不改动任何历史配置,也能让 SSL 证书自动续期
linux·服务器·网络协议·https·ssl
Lsetea4 小时前
curl走HTTPS代理报SSL证书错误:proxy-cacert与cacert双层信任排查
linux·https·ssl证书·curl·代理服务器
菜鸟阿达5 小时前
我把 API 调试工具做成了浏览器版“Postman“,开源了:HTTP/SSE/WebSocket 全能测
http·开源·postman
2501_937860947 小时前
HTTP/HTTPS 学习笔记(中):报头、Cookie、状态码与请求构造
学习·http·https
Peter-Code7 小时前
Nginx 常用操作整理(前端)
服务器·前端·nginx
Lsetea18 小时前
OpenSSL报certificate chain too long:error 22与verify_depth深度排查
linux·https·ssl证书·openssl·证书链
CCblandy21 小时前
HTTP 长连接 3 类故障实测:[WinError 10053]、99 个 TIME_WAIT、69 次多余握手,4 种对策怎么选
后端·python·网络协议·http·云原生·性能优化·架构