WebSocket connection failed with nginx, nodejs and socket.io
Asked Answered
G

1

19

I try to setup nodejs with nginx. But when the client try to connect it fails with...

WebSocket connection to 'ws://www.mydomain.com/socket.io/1/websocket/KUv5G...' failed: Error during WebSocket handshake: 'Connection' header value is not 'Upgrade': keep-alive socket.io.js:2371

So how to enable websocket comunication?

my current nginx config

  upstream mynodejsapp {
    server 127.0.0.1:3000 max_fails=0 fail_timeout=10s weight=1;
    ip_hash;
    keepalive 512;
  }
  server {
    listen 80;
    listen [::]:80 default_server ipv6only=on;
    index index.html;
    server_name mydomain.com www.mydomain.com;
    keepalive_timeout 10;
    gzip on;
    gzip_http_version 1.1;
    gzip_vary on;
    gzip_comp_level 6;
    gzip_proxied any;
    gzip_buffers 16 8k;
    gzip_disable "MSIE [1-6]\.(?!.*SV1)";
    location / {    
      proxy_pass http://mynodejsapp;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-Proto $scheme;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $host;
      proxy_set_header X-NginX-Proxy true;
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection "Upgrade";
      proxy_cache_bypass $http_upgrade;
      proxy_http_version 1.1;
      proxy_redirect off;
      proxy_next_upstream error timeout http_500 http_502 http_503 http_504;
      proxy_connect_timeout 5s;
      proxy_read_timeout 20s;
      proxy_send_timeout 20s;
      proxy_buffers 8 32k;
      proxy_buffer_size 64k;
    }
    location ~ ^/(images/|img/|javascript/|js/|css/|stylesheets/|flash/|media/|static/|robots.txt|humans.txt|favicon.ico) {
      root /var/www/mynodejsapp;
      access_log off;
      expires 1h;
    }
    fastcgi_param   APPLICATION_ENV  production; 
  }
Goles answered 21/12, 2013 at 10:56 Comment(0)
T
35

first,upgrade your nginx server to 1.3 or higher.

second,my nginx conf works.you can follow my conf.

server {
    listen       80;
    server_name jn.whattoc.com;

    location / {
      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:4050/;
      proxy_redirect off;

              proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }
}
Thithia answered 21/12, 2013 at 14:59 Comment(4)
Thanks!, Your tip to upgrade did the trick! I' m on nginx version: nginx/1.4.4 now.Goles
This helped me on nginx/1.18.0 in 2023. Thank you!Pillory
This config helps me to resolve the issue related to WebSocket connection to failed. Thanks.Bradley
I can only see nginx/1.18, how to upgrade nginx :xAmerica

© 2022 - 2024 — McMap. All rights reserved.