无法使用nginx的作为的WebSocket代理(Can't use nginx as we

2019-10-29 08:42发布

这里是我的nginx的配置

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

var socket = io.connect(location.protocol + '//' + document.domain + ':' + (location.port || 80) + namespace)

当我尝试使用include proxy_params; 在nginx的配置行,我得到2018年3月6日19时52分06秒[EMERG] 1#1:打开() “的/ etc / nginx的/ proxy_params” 失败:(2没有这样的文件或目录)在/ etc / nginx的/ conf.d / default.conf:6

我哪里错了,如何让nginx的检索WebSocket连接?

Answer 1:

这在Tomcat中为我工作。 如果你改变应与其他的Web应用程序rooterror_log ,并proxy_pass和配置自己的超时。

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配置

map $http_upgrade $connection_upgrade {
    default upgrade;
    ''  close;
}


文章来源: Can't use nginx as websocket proxy