1. 程式人生 > >解決nginx轉發websocket報400錯誤

解決nginx轉發websocket報400錯誤

socket.io 本地 官方 upgrade lin 通信協議 read 都沒有 hub

解決nginx轉發websocket報400錯誤

說明

由於個人服務器上面有多個項目,配置了二級域名,需要對二級域名進行轉發,在轉發工作這快采取了大名鼎鼎的nginx。在這之前所有的項目運行轉發都沒問題,然而今天在部署一個具有websocket通信的項目時,卻意外的報錯了,錯誤消息如下:

1failed: Error during WebSocket handshake: Unexpected response code: 400

。這個錯誤在本地測試環境以及訪問非nginx轉發都沒有問題,由此推斷出問題應該出現在nginx轉發這個環節。

於是,在google的幫助下,看到了socket.io

官方issues有關於這個問題的討論,鏈接:https://github.com/socketio/socket.io/issues/1942

解決方案

看了下討論區說的方案,問題出現在nginx的配置文件,需要修改nginx.conf文件。在linux終端中敲入vim /etc/nginx/nginx.conf,找到location這個位置,配置文件如下所示:

1server {
2 listen 80;
3 server_name school.godotdotdot.com;
4 charset utf-8;
5
6 location / {
7 proxy_pass http://127.0.0.1:3000;
8 proxy_set_header Host $host;
9 proxy_http_version 1.1;
10 proxy_set_header Upgrade $http_upgrade;
11 proxy_set_header Connection "upgrade";
12 proxy_set_header X-Real-IP $remote_addr;
13 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
14 proxy_connect_timeout 60;
15 proxy_read_timeout 600;
16 proxy_send_timeout 600;
17 }
18
19 error_page 500 502 503 504 /50x.html;
20 location = /50x.html {
21 root html;
22 }
23
24 }

其中最重要的是下面這三行

1proxy_http_version 1.1;
2proxy_set_header Upgrade $http_upgrade;
3proxy_set_header Connection "upgrade";

其中第一行是告訴nginx使用HTTP/1.1通信協議,這是websoket必須要使用的協議。

第二行和第三行告訴nginx,當它想要使用WebSocket時,響應http升級請求。

基於MIT開源協議
本文鏈接:http://blog.godotdotdot.com/2017/12/04/解決nginx轉發websocket報400錯誤/

解決nginx轉發websocket報400錯誤