h_h10a
h_h10a

Reputation: 459

Can't configure Nginx as Reverse Proxy for WebSocket

My Node.js application is running on localhost:8080 These are the server configuration files:

var express = require('express');
var http = require('http');
var app     = express();
var WS      = require('ws');
var config  = require('./config/main');
var Client  = require('./client');
// HTTP
var server = http.createServer(app);
app.use(express.static(__dirname + '/../client/build/'));
server.listen(config.httpPort, function() {
console.info('HTTP listening on *:' + config.httpPort);
});
// WebSocket
var ws = new WS.Server({server: server});
console.info('Websocket server created');
ws.on('connection', function(ws) {
var client = new Client(ws);
console.log('New conection:', client.id);
});

and

module.exports = {
/* HTTP  PORT */
httpPort: process.env.PORT || 8080,

/* WebSocket  PORT */
wsPort: process.env.PORT || 8081
};

So I am trying to run it using the Nginx's reverse proxy:

location /myapp { 
    proxy_pass http://localhost:8080/; 
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}

Now, when I link to localhost/myapp the page appears normally, with all the static files loaded, but it seems like there is no WebSocket connection. PS: I am using Nginx V 1.11.7

Is there something wrong in the configuration or did I miss something? Thank you

Upvotes: 0

Views: 996

Answers (1)

h_h10a
h_h10a

Reputation: 459

Changing the URL that the client uses for the WS connection solved this ..

So in my client side I changed this line: new WebSocket(location.origin.replace(/^http/, "ws")); to this line: new WebSocket("ws://localhost/myapp");

Now it's working fine!

Upvotes: 1

Related Questions