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

相关推荐
handsomestWei3 小时前
Docker引擎API接入配置
运维·http·docker·容器·api
tryCbest9 小时前
Nginx常用操作命令-Linux和Windows系统
linux·windows·nginx
大數據精準工單獲取13 小时前
【数据抓取】 编写爬虫基本请求:使用爬虫框架发送 HTTP 请求,获取网页内容
爬虫·网络协议·http
时空自由民.13 小时前
HTTP协议和MQTT协议区别
网络·网络协议·http
AI_Claude_code14 小时前
网络基础回顾:DNS、IP封锁与HTTP/S协议关键点
网络·爬虫·python·tcp/ip·http·爬山算法·安全架构
難釋懷14 小时前
Nginx实现本地缓存查询
nginx·spring·缓存
ZzzZZzzzZZZzzzz…1 天前
Nginx 平滑升级:从 1.26.3 到 1.28.0,用户无感知
linux·运维·nginx·平滑升级·nginx1.26.3·nginx1.28.0
robch1 天前
python3 -m http.server 8001直接启动web服务类似 nginx
前端·nginx·http
以太浮标1 天前
华为eNSP模拟器综合实验之- DHCP、DNS、HTTP和FTP服务器配置案例Client-Server
linux·服务器·windows·http·华为·信息与通信
cyber_两只龙宝1 天前
【Nginx】Nginx实现FastCGI详解
linux·运维·nginx·云原生·php·memcached·fastcgi