【问题标题】:nginx reverse proxy websocketsnginx 反向代理 websockets
【发布时间】:2013-02-18 01:54:57
【问题描述】:

nginx 现在支持代理 websockets,但是如果没有单独的 location 块适用于使用 websockets 的 URI,我无法找到有关如何执行此操作的任何信息。

我看到一些人推荐这种方法的一些变体:

location / {
    proxy_http_version 1.1;

    proxy_set_header    Upgrade     $http_upgrade;
    proxy_set_header    Connection  "upgrade";

    proxy_pass  http://host:port;
}

这是代理标准 HTTP 和 websocket 的正确方法吗?

我不希望将 Upgrade 标头或 Connection 设置为 upgrade,除非这是浏览器发送的内容,但这些 proxy_set_header 行是 websocket 工作所必需的。

为什么 nginx 不只转发原始的 Upgrade/Connection 标头?

我已经对此进行了实验,发现如果在没有两条 proxy_set_header 行的情况下运行,nginx 不会代理 Upgrade 标头并将 Connection 标头从 upgrade 更改为 close。有了它们,Connectionupgrade 用于非 websocket 请求,这也很糟糕。

【问题讨论】:

    标签: nginx websocket


    【解决方案1】:

    为什么 nginx 不只转发原始的 Upgrade/Connection 标头?

    来自official documentation由于“升级”是逐跳标头,它不会从客户端传递到代理服务器

    RFC 2616


    我不希望将 Upgrade 标头或 Connection 设置为“升级”,除非这是浏览器发送的内容,

    还有一个例子:

    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
    
    server {
        ...
    
        location /chat/ {
            proxy_pass http://backend;
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection $connection_upgrade;
        }
    }
    

    对于非 websocket 请求,连接是“升级”,这也很糟糕。

    您真的知道Connection 标头的含义吗?仅引用 RFC:对于此字段中的每个连接令牌,请从消息中删除与连接令牌同名的任何标头字段。

    怎么会不好?

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 2018-08-06
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 2013-05-04
      • 2020-01-05
      相关资源
      最近更新 更多