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

相关推荐
ZzzZZzzzZZZzzzz…10 分钟前
Nginx 平滑升级:从 1.26.3 到 1.28.0,用户无感知
linux·运维·nginx·平滑升级·nginx1.26.3·nginx1.28.0
robch7 小时前
python3 -m http.server 8001直接启动web服务类似 nginx
前端·nginx·http
以太浮标9 小时前
华为eNSP模拟器综合实验之- DHCP、DNS、HTTP和FTP服务器配置案例Client-Server
linux·服务器·windows·http·华为·信息与通信
cyber_两只龙宝9 小时前
【Nginx】Nginx实现FastCGI详解
linux·运维·nginx·云原生·php·memcached·fastcgi
BullSmall9 小时前
Prometheus 可以监控docker 部署的Nginx 吗?
nginx·docker·prometheus
魔卡少女110 小时前
Nginx配置代码化自动部署詹金斯/Github方案
前端·nginx·github
杨凯凡11 小时前
【002】HTTPS 粗解:证书、TLS 握手与对后端配置的影响
网络协议·http·https
倔强的胖蚂蚁11 小时前
AI 人工智能配置管理 Nginx
运维·nginx·云原生
AI_Claude_code12 小时前
ZLibrary访问困境方案二:DNS-over-HTTPS/TLS配置与隐私保护实践
爬虫·python·网络协议·http·网络安全·https·网络爬虫
邓霖涛12 小时前
nginx使用openSSL自签生成https相关证书
服务器·nginx·https