Nginx配置WebSocket

时间:2022-06-01 17:57:59

Nginx配置WebSocket

server {
    listen       80;
    server_name  example.com;

    location ^~ /socket {
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-NginX-Proxy true;

      proxy_pass http://127.0.0.1:8080/;
      proxy_redirect off;

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

WebSocket 先是通过 HTTP 建立连接,返回101 状态码后切换协议到ws, 在配置里是Upgrade