无法将Nginx配置为WebSocket的反向代理

时间:2016-12-20 09:27:50

标签: node.js nginx websocket port reverse-proxy

我的Node.js应用程序正在localhost:8080上运行 这些是服务器配置文件:

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);
});

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

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

所以我试图使用Nginx的反向代理运行它:

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

现在,当我链接到localhost/myapp时,页面正常显示,加载了所有静态文件,但似乎没有WebSocket连接。 PS:我使用的是Nginx V 1.11.7

配置中有什么问题或我错过了什么吗?谢谢

1 个答案:

答案 0 :(得分:1)

更改客户端用于WS连接的URL解决了这个问题。

所以在我的客户端,我更改了这一行: new WebSocket(location.origin.replace(/^http/, "ws")); 到这一行: new WebSocket("ws://localhost/myapp");

现在工作正常!