• 原配置

    server {
    
    		# 后端api入口
          location ^~ /api/ {
                  proxy_pass http://127.0.0.1:8000;
          }
    	}
    
    
    • 调整后
    • # 如果没有Upgrade头,则$connection_upgrade为close,否则为upgrade
      map $http_upgrade $connection_upgrade {
          default upgrade;
          ''      close;
      }
      # 添加对ws入口的匹配,并且不向下搜索
      location ^~ /api/ws/ {
          proxy_pass http://127.0.0.1:8000;
          proxy_http_version 1.1;
          proxy_set_header Host $host;
          # 下面这两行是关键
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection $connection_upgrade;
      }
      
      # 后端其他api入口
      location ~ /api/ {
              proxy_pass http://127.0.0.1:8000;
      }
      
      
  • 由于websocket是长连接协议 ,多服务器负载均衡建议配置ip hash

    • 也可以考虑使用WebSocketMessageBroker 这类共享会话的消息代理方式实现