Nginx 反向代理 HLS 流媒体方法
现在视频直播很多采用 HLS 传输协议,只需获得 m3u8 链接即可播放,使用简单兼容性好。平时有些 HLS 流媒体速度慢,研究了下如何反代加速。
起初在 Github 上找现成解决方案,不过很少且长时间没更新,测试用不了,索性试试 Nginx 反代。
1. 笔者服务器环境为 CentOS。先添加 EPEL 软件源安装 Nginx。
yum -y install epel-release yum -y install nginx
2. 防火墙放行 HTTP、HTTPS 端口。
firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --permanent --zone=public --add-service=https firewall-cmd --reload
3. 运行 Nginx 服务和设置开机自启动。
systemctl start nginx systemctl enable nginx
4. 编辑 Nginx 站点配置文件,加入下面这段反代规则(注意去掉注释)。
location ~* \.(m3u8|ts|aac)$ { proxy_cache off; # 禁用代理缓存 expires -1; # 禁用页面缓存 proxy_pass http://example.com; # 反代目标 URL sub_filter 'http://example.com/' 'http://$host/'; # 替换 m3u8 文件里的资源链接 sub_filter_last_modified off; # 删除原始响应里的浏览器缓存值 sub_filter_once off; # 替换所有匹配内容 sub_filter_types *; # 匹配任何 MIME 类型 }
5. 保存后用 nginx -t
命令检查语法是否有问题。之后 systemctl restart nginx
重启服务生效。
如果重启服务失败,检查 Nginx 有无内置安装 http_sub_module
模块。
nginx -V 2>&1 | tr ' ' '\n' | grep 'http_sub_module'
例如播放链接 http://example.com/hls/skynews/playlist.m3u8
,将域名改为你服务器 IP 或域名就可以使用了。以下是测试截图。
