Nginx篇之实现nginx转发兼容HTTP和Websocket两种协议

Nginx实现同时兼容http协议和websocket协议

html 复制代码
map $http_upgrade $eop_gateway {
    default "eop-gateway-http";
    websocket "eop-gateway-ws";
}

# 控制 Connection header
map $http_upgrade $connection_upgrade {
    default "keep-alive";    # HTTP 请求
    websocket "upgrade";     # WebSocket 请求
}

upstream eop-gateway-http {
    server XXXXX:8080;
}

upstream eop-gateway-ws {
    server XXXXX:23643;
}

server {
    listen 8888;

    location / {
        proxy_pass http://$eop_gateway;

        # 通用设置
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # WebSocket 设置
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    }
}

参数解释:

重要的是这两行,它表明是websocket连接进入的时候,进行一个连接升级将http连接变成websocket的连接。

启用支持websocket连接:

proxy_set_header Upgrade $http_upgrade;

proxy_set_header Connection "upgrade";

proxy read timeout 表明连接成功以后等待服务器响应的时候,如果不配置默认为60s;

proxy_http_version 1.1;表明使用http版本为1.1

相关推荐
聚美智数13 小时前
网站HTTP状态查询-SEO优化
网络·网络协议·http
云梦谭15 小时前
WebSocket 协议详解:从 HTTP 握手到全双工通信
websocket·网络协议·http
Coisinier17 小时前
docker命令管理镜像及容器
linux·运维·nginx·docker·容器·操作系统
2301_322414280417 小时前
基于web的校园失物招领管理系统59695-计算机毕设 原创(免费领源码+部署教程+开发环境)
mysql·nginx·php·apache·thinkphp·phpstudy·wampserver
flytalei21 小时前
从YAML到Nginx服务访问:动手理解 Kubernetes Pod、Deployment 与 Service
运维·nginx·kubernetes
白帽攻防录1 天前
SRC 挖洞:QUIC 协议栈双 RCE,HTTP/3 的新攻击面怎么挖
网络·网络协议·http·网络安全·http/3
光依旧1 天前
MCP实战手记(十一):MCP接飞书,从机器人到事件订阅的三层深度接入
websocket·事件驱动架构·大模型应用开发·spring ai·企业系统集成·mcp·飞书开放平台
比兔代理1 天前
HTTP 代理与 TLS 指纹:如何避免被识别为代理流量?
网络·网络协议·http
上海云盾-小余1 天前
自定义端口 HTTPS 部署:高防接入遇到的问题与调优方案
网络协议·http·https