自学内容网 自学内容网

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

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

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


原文地址:https://blog.csdn.net/xu710263124/article/details/144141512

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!