nginx 同一个端口支持http和https配置

原理:使用nginx的stream、 stream_ssl_preread模块

由于stream和stream_ssl_preread模块非默认引入,需要在编译安装nginx时引入;编译时添加配置参数 --with-stream --with-stream_ssl_preread_module

1、编译nginx

./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

bash 复制代码
stream {
  upstream  http_gateway {
    server  127.0.0.1:80801;
  }
  upstream  https_gateway {
    server  127.0.0.1:80802;
  }
  map $ssl_preread_protocol $upstream {
    default http_gateway;
    "TLSv1.0" https_gateway;
    "TLSv1.1" https_gateway;
    "TLSv1.2" https_gateway;
    "TLSv1.3" https_gateway;
  }
  
  server {
    listen 8080;
    ssl_preread on;
    proxy_pass $upstream;
  }
  
  upstream http_gateway_8081 {
    server 127.0.0.1:80811;
  }
  upstream https_gateway_4664 {
    server 127.0.0.1:80812;
  }
  map $ssl_preread_protocol $upstream_8081 {
    default http_gateway_8081;
    "TLSv1.0" https_gateway_8081;
    "TLSv1.1" https_gateway_8081;
    "TLSv1.2" https_gateway_8081;
    "TLSv1.3" https_gateway_8081;
  }

  server {
    listen 8081;
    ssl_preread on;
	proxy_pass $upstream_8081;
  }
}

3、简单的nginx.conf示例供参考

bash 复制代码
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;

    server {
       access_log logs/demo-info.log;
		listen 80801;
		listen 80802 ssl;
		server_name localhost;
		ssl_certificate      /usr/local/nginx/conf/ssl/server.crt;
		ssl_certificate_key  /usr/local/nginx/conf/ssl/server.key;
		ssl_session_cache    shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_protocols  TLSv1.2;  
		ssl_prefer_server_ciphers  on;
		ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE; 
		location / {
            proxy_pass http://127.0.0.1:4399;
        }
    }
	server {
		access_log logs/demo-test.log;
		listen 80811;
		listen 80812 ssl;
		server_name localhost;
		ssl_certificate      /usr/local/nginx/conf/ssl/server.crt;
		ssl_certificate_key  /usr/local/nginx/conf/ssl/server.key;
		ssl_session_cache    shared:SSL:1m;
		ssl_session_timeout  10m;
		ssl_protocols  TLSv1.2;  
		ssl_prefer_server_ciphers  on;
		ssl_ciphers  ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;

		location / {
            proxy_pass http://127.0.0.1:4340;
        }
	}

}
相关推荐
CXDNW18 分钟前
【网络篇】计算机网络——应用层详述(笔记)
服务器·笔记·计算机网络·http·web·cdn·dns
秋夫人2 小时前
http cache-control
网络·网络协议·http
叶北辰CHINA2 小时前
nginx反向代理,负载均衡,HTTP配置简述(说人话)
linux·运维·nginx·http·云原生·https·负载均衡
Lansonli4 小时前
云原生(四十八) | Nginx软件安装部署
nginx·云原生·ecs服务器
小白学大数据4 小时前
User-Agent在WebMagic爬虫中的重要性
开发语言·爬虫·http
GodK7777 小时前
HTTPS 的加密流程
网络协议·http·https
加油,旭杏10 小时前
【中间件学习】fastCG介绍和使用
学习·nginx·fastcgi
麻辣韭菜12 小时前
网络基础 【HTTP】
网络·c++·http
苹果醋313 小时前
大模型实战--FastChat一行代码实现部署和各个组件详解
java·运维·spring boot·mysql·nginx
我命由我1234515 小时前
SSL 协议(HTTPS 协议的关键)
网络·经验分享·笔记·学习·https·ssl·学习方法