Nginx配置文件中,如何配置启用SignalR

发布时间 2023-10-11 10:11:40作者: cnkker.com

以下内容包含为 SignalR 启用 WebSocket、ServerSentEvents 和 LongPolling 所需的最低设置:

http {
  map $http_connection $connection_upgrade {
    "~*Upgrade" $http_connection;
    default keep-alive;
  }

  server {
    listen 80;
    server_name example.com *.example.com;

    # Configure the SignalR Endpoint
    location /hubroute {
      # App server url
      proxy_pass http://localhost:5000;

      # Configuration for WebSockets
      proxy_set_header Upgrade $http_upgrade;
      proxy_set_header Connection $connection_upgrade;
      proxy_cache off;
      # WebSockets were implemented after http/1.0
      proxy_http_version 1.1;

      # Configuration for ServerSentEvents
      proxy_buffering off;

      # Configuration for LongPolling or if your KeepAliveInterval is longer than 60 seconds
      proxy_read_timeout 100s;

      proxy_set_header Host $host;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header X-Forwarded-Proto $scheme;
    }
  }
}

使用多个后端服务器时,必须添加粘滞会话(sticky sessions),以防止 SignalR 连接在连接时切换服务器。 可通过多种方法在 Nginx 中添加粘滞会话(sticky sessions)。 下面是其中一种

除了前面的配置外,还添加了以下内容。 在下面的示例中,backend 是服务器组的名称。

对于 Nginx 开放源代码,使用 ip_hash 基于客户端的 IP 地址将连接路由到服务器:(必须是ip_hash 

http {
  upstream backend {
    # App server 1
    server localhost:5000;
    # App server 2
    server localhost:5002;

    ip_hash;
  }
}

最后,将 server 部分中的 proxy_pass http://localhost:5000 更改为 proxy_pass http://backend