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

相关推荐
a***592630 分钟前
用nginx正向代理https网站
运维·nginx·https
Mu.3871 小时前
计算机网络模型
网络·网络协议·计算机网络·安全·http·https
我有一棵树2 小时前
file 协议与 http 协议的区别:为什么本地 HTML 无法加载相对路径 JS,以及正确的解决方式
javascript·http·html
丸子哥哥3 小时前
同一个域名,如何添加多个网站?
服务器·前端·nginx·微服务
r***F2627 小时前
若依部署Nginx和Tomcat
运维·nginx·tomcat
u***42078 小时前
macOs安装docker且在docker上部署nginx+php
nginx·macos·docker
小熊officer10 小时前
Nginx学习
运维·学习·nginx
B***y88514 小时前
配置nginx访问本地静态资源、本地图片、视频。
运维·nginx
zhuyasen21 小时前
Go Web 开发利器:如何让你的 Gin 服务拥有 Nginx 般的静态文件处理能力?
nginx·go·gin
achi01021 小时前
Ubuntu 24.04 LTS 下 Vue 3 开发环境搭建与生产部署完整指南
nginx·node·nvm·vue 3·ubuntu 24·开发环境搭建·国内镜像仓库