【问题标题】:How to configure Nginx reverse proxy for web sockets?如何为 Web 套接字配置 Nginx 反向代理?
【发布时间】:2021-01-11 05:13:34
【问题描述】:

我在 Ubuntu 上运行 ASP Core 应用程序。

在应用程序前面有一个 Nginx 网络服务器用作反向代理,如下所示:

    # Part 1 : Redirect http tp https
    server {
            server_name example.com www.example.com;
            listen 80;
            listen [::]:80;

            return 301 https://www.example.com$request_uri;
    }

    # Part 2 : Reverse proxy for https requests. Get the app response from localhost:5000
    server {
            listen 443 ssl;
            server_name example.com www.example.com;

            ssl_certificate     /home/aspuser/ssl/example.crt;
            ssl_certificate_key /home/aspuser/ssl/example.key;

            access_log /var/log/nginx/reverse-access.log;
            error_log /var/log/nginx/reverse-error.log;

            location / {
                        proxy_pass http://127.0.0.1:5000;
                    }
    }

    # Part 3 : Reverse proxy for websockets on port 3000. Get the app response from localhost:5000/ws
     server {
        listen 3000 ssl;
        server_name example.com www.example.com
        
        ssl_certificate     /home/aspuser/ssl/example.crt;
        ssl_certificate_key /home/aspuser/ssl/example.key;
            
        location / {
              proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header Host $host;

              proxy_pass http://127.0.0.1:5000/ws;

              proxy_http_version 1.1;
              proxy_set_header Upgrade $http_upgrade;
              proxy_set_header Connection "upgrade";
            }    
      }

第 1 部分和第 2 部分工作正常。应用程序正确显示 ssl 证书。

第 3 部分:Websocket 反向代理不工作。当我尝试使用以下 Javascript 从 Chrome Dev Tab 发送 websocket 消息时:

var socket = new WebSocket("wss://www.example.com:3000");

socket.onopen = function(e) {
  console.log("Connection established");
};

我收到了错误:

WebSocket connection to 'wss://www.example.com:3000/' failed: Error in connection establishment: net::ERR_CONNECTION_RESET

相同的应用程序在 localhost 上正常工作(我在 localhost 上得到 websocket 响应),但在 Ubuntu 上发布时不能。 (服务器防火墙允许3000端口)。

有人可以帮忙吗?

【问题讨论】:

    标签: asp.net asp.net-core nginx


    【解决方案1】:

    我相信你的

    proxy_pass http://127.0.0.1:5000/ws;
    

    应该阅读

    proxy_pass http://127.0.0.1:5000/ws/;
    

    我似乎记得当位置以 / 结尾时,转发路径也应该如此。

    【讨论】:

      猜你喜欢
      • 2014-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 2020-09-05
      • 1970-01-01
      相关资源
      最近更新 更多