Nginx forward to solve websocket reported 400 errors
reprint links: https://www.cnblogs.com/duanweishi/p/9286461.html
Note:
Because there are several projects above the personal server, configure the secondary domain name needs to be forwarded to the two domain names, work in this fast-forward took the famous nginx. Before all the projects run forward no problem, but today when you deploy a project has websocket communication, but an unexpected error, the error message is as follows:
1failed: During the WebSocket Handshake Error: Unexpected the Response code: 400
. This error in the local test environment as well as access to non nginx forward, no problems, the problem should appear infer forward this link in nginx.
So, with the help of google and see the issues have socket.io official discussions on this issue, link: https://github.com/socketio/socket.io/issues/1942
Solutions
looked under the forum, said the program, problems in nginx configuration files, you need to modify nginx.conf file. Knock the linux terminal vim /etc/nginx/nginx.conf, to find the location of this location, the configuration file as follows:
···
server {
listen 80;
server_name school.godotdotdot.com;
charset utf-8;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_set_header Host $host;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_connect_timeout 60;
proxy_read_timeout 600;
proxy_send_timeout 600;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
···
Among the most important are the following three lines
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
The first line tells nginx to use HTTP / 1.1 protocol, which is an agreement websoket must be used.
The second and third line tells nginx, when it wants to use WebSocket, upgrade response http request.