如何为socket传递nginx代理URL

时间:2015-05-26 06:22:22

标签: node.js sockets nginx proxy socket.io

我在我的应用程序中使用套接字,我想从nginx传递套接字连接URL作为代理url.I就是这样做

我的套接字代码

var socket = io.connect('/explorer/socket',{
      'reconnect': true,
      'reconnection delay': 500
    });

我的nginx conf

location /explorer/socket {
                proxy_pass    http://xxx.xxx.xx.xxx:3000;
        }

但它无法正常工作,它连接到我的localhost,但我想连接我在nginx中定义的代理网址。那么如何在io.connect中传递代理URL?

2 个答案:

答案 0 :(得分:2)

你必须改变像这样的nginx configuartion

location /socket.io/ {
                proxy_pass    http://xxx.xxx.xx.xxx:3000;
                 proxy_pass http://127.0.0.1:8080;
proxy_http_version 1.1;

proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “upgrade”;
proxy_read_timeout 86400;

access_log off;
error_log /opt/nginx/logs/websockets.error.log;


        }

1)/socket.io/ - 这会告诉nginx将你的套接字调用传递给给定的ip

现在更改套接字代码

var socket = io.connect('/',{
      'reconnect': true,
      'reconnection delay': 500
    });

答案 1 :(得分:0)

尝试更改您的nginx.conf的位置,如下所示;

location /explorer/socket {
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_pass http://xxx.xxx.xx.xxx:3000;
}

来源:http://nginx.com/blog/nginx-nodejs-websockets-socketio/