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

Can't configure Nginx as Reverse Proxy for WebSocket

我的 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";
}

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

配置有问题还是我遗漏了什么?谢谢

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

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

现在一切正常!