nginx 反向代理 websocket

2024-05-06

nginx 现在支持代理 websockets,但我无法找到任何有关如何在没有单独的情况下执行此操作的信息location应用于使用 websocket 的 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_headerwebsocket 需要线路才能工作。

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

我对此进行了实验,发现 nginx 不代理Upgrade标题并更改Connection标头至close from upgrade如果没有两个就运行proxy_set_header线。跟他们,Connection is upgrade对于非 websocket 请求,这也很糟糕。


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

来自官方文档 http://nginx.org/en/docs/http/websocket.html: 由于“Upgrade”是逐跳标头,因此它不会从客户端传递到代理服务器

See RFC 2616 https://www.rfc-editor.org/rfc/rfc2616#section-13.5.1.


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

还有一个例子:

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 的一段话:对于此字段中的每个连接令牌,从消息中删除与连接令牌同名的任何标头字段。

怎么会坏呢?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

nginx 反向代理 websocket 的相关文章

随机推荐