【问题标题】:How to get nginx to serve websockets from a directory?如何让 nginx 从目录中提供 websockets 服务?
【发布时间】:2015-12-03 05:24:41
【问题描述】:

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

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

我的 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']
  });

我做错了什么?

【问题讨论】:

标签: node.js nginx websocket socket.io


【解决方案1】:

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

Correct proxy path in nginx.conf

【讨论】:

    猜你喜欢
    • 2018-01-17
    • 2015-09-28
    • 1970-01-01
    • 2018-12-05
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    相关资源
    最近更新 更多