首页 > 解决方案 > 代理在 nginx 上传递 Socket.IO 连接不起作用

问题描述

我正在尝试使用 nginx 代理传递 node.js-socket.io 应用程序。

客户端是一个包含一些 javascript 的 html 文件;

<html>
<head>
<script src="socket.io.js"></script>
<script>
    var socket = io('http://localhost:80');
    socket.on('welcome', function(data){
        console.log('Server says:' + data);
        socket.emit('client-response', 'thank you!');
    });
</script>
</head>
<body>
Socket.io
</body>
</html>

应该在 nginx.conf 文件中代理传递的服务器块是这样的;

server {
        listen       80;
        listen       [::]:80;
        #root         /usr/share/nginx/html;
        include /etc/nginx/default.d/*.conf;

        location / {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_pass "http://localhost:2156";
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

我的 node.js 应用程序在端口“2156”中启动并运行。

当我对此进行测试时,客户端尝试访问端口 80 上的 socket.io 并失败并出现 404 错误(因为 nginx 应该将代理传递到端口 2156 但它没有)。

我在这里想念什么?

标签: node.jsnginxsocket.ioproxypass

解决方案


编辑:我已经将客户端更改为连接"http://localhost/socket.io/"并重写了 nginx.conf,如下所示:

server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        root         /usr/share/nginx/html;

        location /socket.io/ {
            proxy_http_version 1.1;
            proxy_set_header Upgrade $http_upgrade;
            proxy_set_header Connection "Upgrade";
            proxy_set_header Host $host;
            proxy_pass http://localhost:2156/socket.io/;
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

它奏效了。


推荐阅读