以下内容包含为 SignalR 启用 WebSocket、ServerSentEvents 和 LongPolling 所需的最低设置:
核心代码:
- http {
-
- map $http_connection $connection_upgrade {
- "~*Upgrade" $http_connection;
- default keep-alive;
- }
-
- server {
- listen 80;
- server_name xx.xxx.com;
- location / {
- proxy_pass http://backend;
- proxy_set_header Host $host;
- root html;
- index index.html index.htm;
- }
- # SignalR 单独配置
- location /chatHub {
- proxy_pass http://backend;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection $connection_upgrade;
- proxy_http_version 1.1;
- }
- }
-
- }
使用多个后端服务器时,必须添加粘滞会话(sticky sessions),以防止 SignalR 连接在连接时切换服务器。 可通过多种方法在 Nginx 中添加粘滞会话(sticky sessions)。 下面是其中一种
除了前面的配置外,还添加了以下内容。 在下面的示例中,backend 是服务器组的名称。
对于 Nginx 开放源代码,使用 ip_hash 基于客户端的 IP 地址将连接路由到服务器:(必须是ip_hash )
- upstream backend {
- server 192.168.0.245:8000;
- server 192.168.0.245:8001;
- server 192.168.0.245:8002;
- ip_hash; # 根据客户端IP地址Hash值将请求分配给固定的一个服务器处理
- }
全部代码:
- worker_processes 1;
- events {
- worker_connections 1024;
- }
-
- http {
- include mime.types;
- default_type application/octet-stream;
-
- map $http_connection $connection_upgrade {
- "~*Upgrade" $http_connection;
- default keep-alive;
- }
-
- sendfile on;
- keepalive_timeout 65;
-
- server {
- listen 80 default_server;
- server_name _;
- return 444 ; #过滤其他域名的请求,返回444状态码
- }
-
-
-
- upstream backend {
- server 192.168.0.245:8000;
- server 192.168.0.245:8001;
- server 192.168.0.245:8002;
- ip_hash; # 根据客户端IP地址Hash值将请求分配给固定的一个服务器处理
- }
-
- server {
- listen 80;
- server_name xx.xxx.com;
- location / {
- proxy_pass http://backend;
- proxy_set_header Host $host;
- root html;
- index index.html index.htm;
- }
- # SignalR 单独配置
- location /chatHub {
- proxy_pass http://backend;
- proxy_set_header Upgrade $http_upgrade;
- proxy_set_header Connection $connection_upgrade;
- proxy_http_version 1.1;
- }
-
- error_page 500 502 503 504 /50x.html;
- location = /50x.html {
- root html;
- }
- }
-
- }
-