为socket-io和nodejs设置nginx

时间:2015-04-17 06:58:50

标签: javascript node.js sockets nginx

我有一个项目,直到现在都不需要socket-io,具有以下nginx配置

server {
    server_name app.web.com;
    root /var/www/app/releases/current/public/;
    index index.html index.htm;

    access_log /var/log/nginx/app.access.log;
    error_log  /var/log/nginx/app.error.log;
    underscores_in_headers on;

    recursive_error_pages on;
    error_page 503 @maintenance;

    if (-f $document_root/system/maintenance.html) {
        return 503;
    }

    location @maintenance {
        error_page 405 = /system/maintenance.html;
        rewrite  ^(.*)$  /system/maintenance.html break;
    }

    location ~ ^/(js|css|images|media|system)/ {
        autoindex off;
        add_header Cache-Control public;
        expires 4w;
    }

    location / {
        try_files $uri $uri/index.html @proxy;
    }

    location @proxy {
        proxy_set_header Host $http_host;
        proxy_pass   http://127.0.0.1:7485;
    }
}

现在我使用socket-io在其中添加了聊天功能。如何从nginx添加启用套接字?

1 个答案:

答案 0 :(得分:0)

您应该将socket.io配置为serve on specific path(例如/socketio) 何时应在Nginx配置中添加以下内容:

location /socketio {
    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_buffering off;
    proxy_redirect off;
    proxy_pass http://127.0.0.1:4000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;
    proxy_set_header X-Forwarded-Proto https;
    break;
}

更改http://127.0.0.1:4000以解决应用中socket.io的监听问题。