不能将nginx用作websocket代理

时间:2018-03-06 20:29:57

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

这是我的nginx配置

server {
    listen 80;
    server_name _;

    location / {
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_pass http://flask:8001;
    }

    location /socket.io {

        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_buffering off;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "Upgrade";
        proxy_pass http://flask:8001/socket.io;
    }
}

基于this代码的应用

因此,我无法通过代码

从我的客户端页面连接到websocket
var socket = io.connect(location.protocol + '//' + document.domain + ':' + (location.port || 80) + namespace)

当我尝试在nginx配置中使用include proxy_params;行时,我得到2018/03/06 19:52:06 [emerg] 1#1:open()" / etc / nginx / proxy_params&# 34; /etc/nginx/conf.d/default.conf:6中失败(2:没有这样的文件或目录)

我错在哪里以及如何允许nginx检索websocket连接?

1 个答案:

答案 0 :(得分:1)

这在tomcat中对我有用。如果您更改rooterror_logproxy_pass并配置自己的超时,则应与其他网络应用程序配合使用。

server {
    listen       80;
    listen       443 ssl;
    server_name  x.y.com;
    root         /opt/tomcat/webapps/;

    error_log    /var/logs/nginx/x.y.com.log debug;

    ssl_certificate         /root/program/ssl/certificate.pem;
    ssl_certificate_key     /root/program/ssl/certificate.key;

    # Load configuration files for the default server block.
    include /etc/nginx/default.d/*.conf;

    location / {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header Host $http_host;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Connection "";
        proxy_connect_timeout  4000s;
        proxy_read_timeout     4000s;
        #proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        #proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
        proxy_pass http://127.0.0.1:8080/;
    }

还将此添加到我的http配置

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''  close;
}