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

相关推荐
张赐荣2 小时前
sslx: 一个检测、查看 HTTPS 证书信息的跨平台单文件命令行工具
网络协议·http·https
RacentCLM4 小时前
HTTPS只在登录时有用?关于TLS的误解讲清
数据库·网络协议·https
李迟4 小时前
Nginx容器绑定81端口报拒绝访问错误的解决
运维·nginx
杨云龙UP4 小时前
生产实战:Keepalived + Nginx + MySQL 双向复制高可用架构部署与原理详解
运维·数据库·mysql·nginx·架构·keepalived·高可用架构
m0_639906945 小时前
RESTful API 接口设计规范:资源导向、HTTP 语义、统一返回格式、避坑指南
http·restful·设计规范
洋不写bug5 小时前
HTTP(二):万字解析HTTP交互的请求、响应报文格式
网络协议·http·交互·postman·请求格式·响应格式·restful规范
洋不写bug7 小时前
HTTP(一):Fiddler下载、抓包请求响应解析
网络协议·http·fiddler·网络通信·抓包·http请求和响应
隐擎fox7 小时前
解密 HTTP/2 帧时序与流控指纹:Akamai H2 指纹逆向检测与协议重塑工程实战
网络·网络协议·tcp/ip·http
艾莉丝努力练剑8 小时前
【AI大模型接入SDK】Trae生成main方法
网络·人工智能·网络协议·http·架构·1024程序员节
国际云,接待8 小时前
云服务器 WebSocket 空闲后频繁断开:查 Nginx 超时、心跳与负载均衡,再评估扩容
服务器·websocket·nginx