如何让nginx从目录中提供websockets?

时间:2015-09-07 15:52:13

标签: node.js nginx websocket socket.io

我试图让nginx从端口80上的目录提供websockets,而不是node.js正在侦听的端口上的根域。

直接连接到端口是可行的,但是尝试通过nginx配置中指定的目录进行连接我在使用curl时不断从浏览器和301获取代码502.

我的nginx服务器配置如下:

server {
    listen 80 default_server;
    listen [::]:80 default_server ipv6only=on;

    root /www;
    index index.html index.htm index.php;

    server_name my_ip;

    location /smth-chat/ {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_set_header X-NginX-Proxy true;

        proxy_pass http://127.0.0.1:3335;
        proxy_redirect off;

        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

    location / {
        try_files $uri $uri/ =404;
    }

    location /something-something/ {
        try_files $uri $uri/ /something-something/index.php?q=$uri&$args;
    }

    location ~ \.php$ {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;

        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

my_ip / something-something / chat提供了一个带有socket.io聊天的html页面,它试图通过websocket连接到my_ip / smth-chat(在socket.io设置中强制执行)。

我的nginx error.log中的条目如下所示:

2015/09/07 17:42:15 [error] 19277#0: *264 upstream prematurely closed connection while reading response header from upstream, client: some_ip, server: my_ip, request: "GET /smth-chat/?EIO=3&transport=websocket HTTP/1.1", upstream: "http://127.0.0.1:3335/smth-chat/?EIO=3&transport=websocket", host: "my_ip"

客户端socket.io以:

启动
  var socket = io('http://my_ip', {
    path: '/smth-chat',
    transports: ['websocket']
  });

我做错了什么?

1 个答案:

答案 0 :(得分:0)

您的问题是您的nginx配置允许与/en的连接,它应该只允许/en/。看一下这个。

Correct proxy path in nginx.conf