Analysis
Websocket头部中端到端的头部信息需要被转发,因此需要在Nginx配置文件中对Websocket头部进行配置。
Actions
-
找到Websocket头部依赖的头部信息
Websocket依赖的头部信息主要有两个:
Connection 、 Upgrade
-
在Nginx配置文件中配置Websocket代理
server { listen 80; listen [::]:80 server_name your-website.com #this where socket io will be handling the request location /socket.io/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass "http://localhost:8000/socket.io/"; } location / { proxy_pass "http://localhost:8000"; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection 'upgrade'; proxy_set_header Host $host; proxy_cache_bypass $http_upgrade; } error_page 404 /404.html; location = /40x.html{ } error_page 500 502 503 504 /50x.html; location = /50x.html{ } }
Especially Note:
- 显示设置Http版本信息1.1
- 增加需要转发的头部信息(connection and upgrade)
- 【Don't Forget】请求中如果带有socket io,需要增加代理 /socket.io/
-
Save the config file
Test & Taste
nginx -t
nginx -s reload
Bonus
顺便解决【Webrtc】Chrome浏览器无法直接(if your websocket use http)调用摄像头的问题?采用语句navigator.mediaDevices.getUserMedia
调用摄像头的条件是要么localhost要么是https连接,所以如果不是在本地调用,就需要采用https安全协议,因此可以通过给Nginx添加CA证书(详见:简单搭建HTTPS or Install certbot(https))后通过代理转到http的Websocket端口。
Ref
how-to-proxy-websockets-with-nginx:
https://blog.usejournal.com/how-to-proxy-websockets-with-nginx-e333a5f0c0bb
网友评论