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

相关推荐
xixingzhe25 小时前
SpringBoot + Nginx 免鉴权接口安全防护方案
运维·nginx·安全
HelloWorld工程师9 小时前
新手如何快速申请SSL通配符证书...
网络协议·https·ssl
酷炫的水壶12 小时前
使用memc-nginx和srcache-nginx模块构建高效透明的缓存机制
运维·nginx·缓存
智商偏低14 小时前
Windows Nginx 完整安装 + 启动教程
运维·nginx
念何架构之路18 小时前
moby-http-api-server
网络·网络协议·http
oscar99918 小时前
3.4 Nginx 负载均衡——动态再平衡的反人性纪律
nginx·github·负载均衡·财富源代码
魔尔助理顾问20 小时前
HTTP Response中的CORS Headers
网络·网络协议·http
川石课堂软件测试20 小时前
性能测试|Nginx中间件监控与调优
linux·python·nginx·中间件·单元测试·压力测试·harmonyos
m0_740859621 天前
Nginx进行配置文件拆分(以windows解压版为例)
nginx
开发小程序的之朴1 天前
认识安企CMS-安装安企CMS的环境要求
nginx·golang·系统架构