Flask - 使用 Nginx 隐藏在反向代理后面的 SocketIO

Flask - SocketIO hidden behind reverse proxy with Nginx

我想将 Flask-SocketIO 与我的 Flask 项目集成。我的应用 运行 在 Nginx 反向代理后面:

location /plivo_api{
       rewrite ^/plivo_api(.*) / break;
       proxy_pass http://127.0.0.1:8090;
}

所以我不明白 /plivo_api 中收到的所有流量将被重写为“/”端口 8090。这部分效果很好。

当我想连接到套接字时,问题就开始了。直接连接socket没问题

# all those examples work
# from localhost
var socket = io.connect()
var socket = io.connect('http://localhost:8090/')
# running the app out of the reverse proxy
var socket = io.connect('http://my_server:8090/')

但是通过 Nginx 我无法连接

# Bad Gateway
var socket = io.connect('http://my_server/plivo_api')

问题是我是否缺少连接到我的 socketio 应用程序的东西,或者是否有一些额外的东西要添加到 Nginx 配置中?

带有 socketio 集成的 flask 应用程序代码看起来像

# this code work well, the flask app and socket io
# problem must be in Ngin settings.
The flask app code with socketio integration looks like 
from flask import Flask, render_template
from flask_socketio import SocketIO, emit

HOST = '127.0.0.1'
PORT = 8090

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
app.config['DEBUG'] = True
app.config['SERVER_NAME'] = f'{HOST}:{PORT}'
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    socketio.run(app, port=PORT, host=HOST)

您需要在 nginx 中为 Socket.IO 端点创建一个特殊的位置块。您不能像对 HTTP 路由那样使用常规 URL。

documentation有个例子:

server {
    listen 80;
    server_name _;

    location /socket.io {
        include proxy_params;
        proxy_http_version 1.1;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://127.0.0.1:5000/socket.io;
    }
}