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

相关推荐
冰橙子id1 小时前
centos7编译安装LNMP架构
mysql·nginx·架构·centos·php
栗子叶4 小时前
两种Https正向代理的实现原理
网络协议·http·https·正向代理
玩转4G物联网20 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与TCP服务器通信
服务器·网络·物联网·网络协议·tcp/ip·http·fs100p
米粉030521 小时前
深入剖析Nginx:从入门到高并发架构实战
java·运维·nginx·架构
hie9889421 小时前
HTTP常见的请求方法、响应状态码、接口规范介绍
http
一曝十寒1 天前
那些常见的 HTTP 状态码
前端·http
静水楼台x1 天前
nginx日志的一点理解
运维·nginx
欧先生^_^1 天前
ingress-nginx 开启 Prometheus 监控 + Grafana 查看指标
nginx·grafana·prometheus
眠修1 天前
Nginx + Tomcat负载均衡群集
nginx·tomcat·负载均衡
酷爱码1 天前
在 Linux 中修改 Apache HTTP Server(httpd)默认端口的完整指南
linux·http·apache