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 小时前
HTTPS
网络协议·http·https
W.A委员会4 小时前
常见网络攻击
网络·http·网络安全
Watermelo6176 小时前
理解 JavaScript 中的“ / ”:路径、资源与目录、nginx配置、请求、转义的那些事
前端·javascript·vue.js·chrome·nginx·正则表达式·seo
Cyber4K9 小时前
【Nginx专项】高级进阶架构篇-Location、Rewrite及HTTPS
服务器·nginx·架构·https
博风9 小时前
nginx:前后端分离常用配置
nginx
思麟呀9 小时前
应用层协议HTTP
linux·服务器·网络·c++·网络协议·http
pengyi87101512 小时前
共享IP使用基础注意事项,从源头降低关联风险
网络·网络协议·tcp/ip·安全·http
思麟呀13 小时前
HTTP的Cookie和Session
linux·网络·c++·网络协议·http
PinTrust SSL证书13 小时前
Geotrust企业型OV通配符SSL
网络协议·网络安全·小程序·https·云计算·ssl
七七powerful14 小时前
Nginx 日志切割完全指南:从原理到生产实战
运维·nginx