3

I have nginx configured to proxy websockets like this:

location /socket.io {
proxy_pass http://localhost:8000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";

}

The clients connect fine but when the server emits a notification:

io.sockets.emit("update",data);

the client never receives it:

var socket = io.connect("http://" + hostip + "/socket.io");
socket.on("update",function(data)
{
  console.log("got update: " + data);
});

If I bypass nginx everything works as expected:

var socket = io.connect("http://" + hostip + ":8000");
socket.on("update",function(data)
{
  console.log("got update: " + data);
});

What am I missing? As an aside, why isn't the bypassing of nginx a single origin policy violation? Thanks.

Hilo
  • 869
  • 2
  • 9
  • 24

1 Answers1

6

Try just var socket = io.connect(location.host); in the browser. I don't think you want the /socket.io path.

Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • Yep, I'm running nginx 1.4.1 My code is identical to your linked answer. The client connects fine, the server logs debug to the console about the heartbeat of the client, it logs when it emits the "update" but the client never receives it. – Hilo May 24 '13 at 23:54
  • the /socket.io in the path is a virtual location which is mapped to localhost:8000 by nginx as configured. – Hilo May 25 '13 at 16:04
  • Yes I know, but socket.io has that path hard coded. Just connect to the root and socket.io will make a GET to a URL like `/socket.io/1/websocket/FDzfeZaDH_tuk7bulcz5` automatically. – Peter Lyons May 25 '13 at 16:22
  • 1
    Thanks Peter, that solved the problem. I would appreciate a little clarification. As you stated, it seems that the io.connect() call is adding a /socket.io to the url which explains why nginx routes it correctly to my socket.io server. Given that, when I have the /socket.io in the url, the io.connect() generates the same GET URL as it does the location.host, why doesn't it work? – Hilo May 25 '13 at 21:45
  • 1
    I grovel at your feet with gratitude! At long last, my configuration is complete! – Fresheyeball May 30 '13 at 19:54
  • @PeterLyons kindly have a look at this http://stackoverflow.com/questions/23103241/how-to-redirect-web-sockets-connection-through-nginx . I am very much stuck here. – Surender Thakran Apr 16 '14 at 08:22