不能将Nginx用作WebSocket代理 [英] Can't use nginx as websocket proxy
问题描述
这是我的Nginx配置
Here is my nginx config
server {
listen 80;
server_name _;
location / {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_pass http://flask:8001;
}
location /socket.io {
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_buffering off;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "Upgrade";
proxy_pass http://flask:8001/socket.io;
}
}
针对基于此代码
结果是,我无法通过代码从客户端页面连接到websocket
As a result, I can't connect to websocket from my client page by code
var socket = io.connect(location.protocol + '//' + document.domain + ':' + (location.port || 80) + namespace)
当我尝试在nginx配置中使用include proxy_params;
行时,我得到2018/03/06 19:52:06 [emerg] 1#1:open()"/etc/nginx/proxy_params"失败(2:否这样的文件或目录)在/etc/nginx/conf.d/default.conf:6
When I try to use include proxy_params;
line in nginx config I get 2018/03/06 19:52:06 [emerg] 1#1: open() "/etc/nginx/proxy_params" failed (2: No such file or directory) in /etc/nginx/conf.d/default.conf:6
哪里错了,以及如何允许Nginx检索websocket连接?
Where I'm wrong and how to allow nginx to retrieve websocket connections?
推荐答案
这在tomcat中对我有用.如果更改root
,error_log
和proxy_pass
并配置自己的超时时间,则应该可以与其他Web应用程序一起使用.
This worked for me in tomcat. should work with other web applications if you change root
, error_log
, and proxy_pass
and config your own time outs.
server {
listen 80;
listen 443 ssl;
server_name x.y.com;
root /opt/tomcat/webapps/;
error_log /var/logs/nginx/x.y.com.log debug;
ssl_certificate /root/program/ssl/certificate.pem;
ssl_certificate_key /root/program/ssl/certificate.key;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $http_host;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Connection "";
proxy_connect_timeout 4000s;
proxy_read_timeout 4000s;
#proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
#proxy_set_header X-Forwarded-Proto $proxy_x_forwarded_proto;
proxy_pass http://127.0.0.1:8080/;
}
还将此添加到了我的http配置
Also added this to my http config
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
这篇关于不能将Nginx用作WebSocket代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!