nginx 代理 ws协议
ws协议在http之上,直接在http协议里面进行协议升级即可
正常的http请求正常,ws请求也正常,使用同一个端口
正常的ws请求截图
代理配置
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
charset utf-8;
#tcp_nopush on;
keepalive_timeout 120;
client_header_buffer_size 10240k;
server {
listen 8900;
server_name localhost;
# 使用正则表达式过滤我需要的请求进行协议升级
location ~* /sms/.*\.(flv|hls)$ {
proxy_pass http://YOUR_WS_SERVER:PORT;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
location / {
root html;
}
error_page 500 502 503 504 /50x.html;
}
}
前端测试文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
<script>
var ws = new WebSocket('ws://127.0.0.1:8900/sms/xxxx/wyyyyyyy.flv?token=');
console.log('ws连接状态:' + ws.readyState);
console.log(ws)
</script>
</html>
location /xxxxx {
# 正常请求的请求头host中已经包含了主机和端口信息
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# 升级websocket协议使用
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 6000s; # 没明白这个的含义,没看懂官方的这个说明,默认值为60s
...
}