我在AWS EC2实例上为我的node.js应用程序运行nginx。我想使用websockets(socket.io)和普通的http请求/响应。我的问题是,每当我有一个从我的移动设备到服务器的活动套接字连接并尝试发出正常的http请求时,将调用移动设备的socket.io错误函数,并显示消息" 502 Bad网关"
只有套接字有效。只有正常的http请求也可以。
我发现,在我将nginx设置为仅使用https之后发生了这个问题。
这是我在/ sites-enabled / sites-available中的nginx配置:
server {
listen 80;
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
if ($scheme != "https") {
rewrite ^ https://$host$request_uri? permanent;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
Nginx错误日志:
[error] 14117#14117: *50 upstream prematurely closed connection while reading response header from upstream, client: 78.94.9.226, server: example.com, request: "GET /socket.io/?transport=polling&b64=1&sid=rgXMQhL6mbSET8ktAAAA HTTP/1.1", upstream: "http://127.0.0.1:3000/socket.io/?transport=polling&b64=1&sid=rgXMQhL6mbSET8ktAAAA", host: "example.com"
iOS错误日志:
LOG SocketIOClient: Handling event: error with data: ["Got unknown error from server <html>\r\n<head><title>502 Bad Gateway</title></head>\r\n<body bgcolor=\"white\">\r\n<center><h1>502 Bad Gateway</h1></center>\r\n<hr><center>nginx/1.10.3 (Ubuntu)</center>\r\n</body>\r\n</html>\r\n"]
如果您需要更多信息,请与我们联系!
答案 0 :(得分:1)
将您的nginx配置更改为两个块
server {
listen 80;
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
if ($scheme != "https") {
rewrite ^ https://$host$request_uri? permanent;
}
location /socket.io {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $host;
}
}
您只想升级socket.io
而非其他网址
答案 1 :(得分:1)
我自己解决了这个问题。这是一个非常愚蠢的问题。我在我的node.js服务器文件夹中创建了一个名为access.log的文件,并告诉摩根记录器写入文件。我忘了的是,只要服务器文件夹中的代码发生变化,我就会使用PM2来重启服务器。因此,每当我发出http请求并且套接字断开连接时,PM2都会重新启动服务器。