2
votes

I have nginx running on localhost serving static html/css/js files. It proxies to a remote server for the required RESTful db services. I need to also setup nginx to proxy to a remote websocket server but failing miserably with all attempts.

The Javascript client works if I hardcode the websocket server url like this:

socket = new WebSocket("ws://50.29.123.83:9030/something/socket");

Obviously, not a optimal solution and I should be able to use location.host and a proxy to get to the same location. I configured nginx with the following:

http {
  ...
  upstream websocket {
    server 50.29.123.83:9030;
    }
}

sever {
  ...
  location /the_socket/ {
        proxy_pass http://websocket;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
  }
}

Then updated the client code to:

socket = new WebSocket("ws://" + location.host + "/the_socket/something/socket");

This fails with the following error:

WebSocket connection to 'ws://localhost/the_socket/something/socket' failed: Error during WebSocket handshake: Unexpected response code: 404

What am I doing wrong?

  • ip & port numbers changed to protect the innocent
1
It looks like location.host is referencing localhost which is probably pointing to the local nginx instance, but if they are the same thing, then there's also the issue that location.host is also not including the port in the urlPatrick Barr
location.host is referencing localhost where the local nginx is running. the port is specified in the proxy_pass via the upstream server declaration.Hilo
You will be accessing the remote server with /the_socket/something/socket, as you have not attempted to remove the prefix.Richard Smith
@RichardSmith could you please elaborate, I'm not sure what you are referring to. Thanks.Hilo

1 Answers

2
votes

Your proxy statement will pass the URI to the upstream server unmodified. That is the text /the_socket will still be attached to the beginning of the URI.

If you want proxy_pass to modify the URI and remove the location value - you should add a URI to the proxy_pass statement. For example:

location /the_socket/ {
    proxy_pass http://websocket/;
    ...
}

See this document for details.