nginx反向代理websockets [英] nginx reverse proxy websockets

查看:862
本文介绍了nginx反向代理websockets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

nginx now supports proxying websockets, but I was unable to find any information on how to do this without having a separate location block that applies to URIs on which websockets are used.

我见过一些人推荐这种方法的一些变体:

I've seen some folks recommending some variations of this approach:

location / {
    proxy_http_version 1.1;

    proxy_set_header    Upgrade     $http_upgrade;
    proxy_set_header    Connection  "upgrade";

    proxy_pass  http://host:port;
}

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

Would that be the correct way to proxy standard HTTP as well as websockets?

除非浏览器发送了Upgrade标头或Connection设置为upgrade,否则我不希望将其设置为upgrade,但是这些proxy_set_header行是websocket正常工作所必需的.

I don't want the Upgrade header or Connection being set to upgrade unless that's what the browser sent, but these proxy_set_header lines are required for websockets to work.

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

Why doesn't nginx just forward the original Upgrade/Connection headers?

我对此进行了实验,发现如果没有两条proxy_set_header行,nginx不会代理Upgrade头,并且会将Connection头从upgrade更改为close.有了它们,对于非websocket请求,Connectionupgrade,这也很糟糕.

I've experimented with this and found that nginx does not proxy the Upgrade header and changes the Connection header to close from upgrade if running without the two proxy_set_header lines. With them, Connection is upgrade for non-websocket requests, which is also bad.

推荐答案

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

Why doesn't nginx just forward the original Upgrade/Connection headers?

官方文档中:因为升级"为逐跳标头,它不会从客户端传递到代理服务器

请参见 RFC 2616 .

除非浏览器发送了此邮件,否则我不希望将Upgrade标头或Connection设置为"upgrade",

I don't want the Upgrade header or Connection being set to "upgrade" unless that's what the browser sent,

还有一个例子:

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 is 'upgrade' for non-websocket requests, which is also bad.

您实际上知道Connection标头是什么意思吗?只是来自RFC的一句话:对于此字段中的每个连接令牌,请从邮件中删除与该连接令牌同名的所有标头字段.

Do you actually know what the Connection header means? Just a quote from RFC: for each connection-token in this field, remove any header field(s) from the message with the same name as the connection-token.

怎么可能不好?

这篇关于nginx反向代理websockets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆