【问题标题】:websockets in openresty proxyopenresty 代理中的 websockets
【发布时间】:2021-07-20 13:08:48
【问题描述】:

我使用 OpenResty 使用 MFA 创建了代理,它主要工作正常。

但我对 websockets 有疑问:Firefox 说它“无法与服务器 wss://...连接”。查看浏览器的网络面板,我可以看到切换协议请求似乎没问题。我的 nginx.conf 如下所示:

worker_processes  auto;

env TARGET_APPLICATION_HOST;
env TARGET_APPLICATION_PORT;
env TARGET_USE_SSL;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name localhost;
        
        location / {
            resolver local=on ipv6=off valid=100s;  
            
            content_by_lua_block {
                local http = require "resty.http"
                local httpc = http.new()
                
                httpc:set_timeout(500)                         
                local ok, err = httpc:connect(
                    os.getenv("TARGET_APPLICATION_HOST"),
                    os.getenv("TARGET_APPLICATION_PORT"))

                if not ok then
                    ngx.log(ngx.ERR, err)
                    return
                end

                if os.getenv("TARGET_USE_SSL") == "TRUE" then
                    -- Trigger the SSL handshake
                    session, err = httpc:ssl_handshake(False, server, False)  
                end

                httpc:set_timeout(2000)                         
                httpc:proxy_response(httpc:proxy_request())
                httpc:set_keepalive()                       
            }                   
        }
    }    
}

它是生产代理的更简单版本,但与 websockets 返回相同的错误。我尝试将代理与纯 nginx 一起使用,它可以与 websockets 一起使用,但我需要 OpenResty 的功能(基于 cookie 值代理不同的主机)。

上面的文件有没有简单的错误或者OpenResty没有websocket能力?

【问题讨论】:

    标签: nginx websocket reverse-proxy openresty


    【解决方案1】:

    lua-resty-http 是一个 HTTP(S) 客户端库,它不(也可能不会)支持 WebSocket 协议。

    WebSocket 协议还有另一个库:lua-resty-websocket。它实现了客户端和服务器,所以应该可以使用这个库编写代理。

    我需要 OpenResty 的能力(根据 cookie 值代理不同的主机)

    ngx.balancer 完全符合您的需求,请查看examplethis answer

    【讨论】:

    • ngx.balancer 支持 websockets 吗?我在它的页面上没有任何关于它的信息。
    • ngx.balancer 本身不做代理,它只是一个 API “允许您根据每个请求从列表中动态选择一个后端对等点连接(或重试)后端对等点也可能是动态的”。如果ngx_http_proxy_module 支持WebSockets(和it does),那么应该可以将ngx.balancer + proxy_pass 用于WebSockets。
    • 谢谢,我去测试一下。
    猜你喜欢
    • 2012-03-25
    • 2013-05-04
    • 2016-03-22
    • 2011-08-09
    • 2013-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-10-17
    • 2012-02-19
    相关资源
    最近更新 更多