Flask - SocketIO隐藏在Nginx的反向代理背后

时间:2018-04-12 16:54:51

标签: python nginx flask reverse-proxy flask-socketio

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

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

所以我不准确 / plivo_api 中收到的所有交通将被重新编辑为" /"端口 8090 。这部分效果很好。

当我想连接到套接字时,

问题开始。直接连接到套接字没有问题。

# 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集成的烧瓶应用代码看起来像

# 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)

1 个答案:

答案 0 :(得分:2)

您需要在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;
    }
}