4

借助 Nginx 搭建带简单认证的直播推流服务器,实现多平台同步直播

 2 years ago
source link: https://blog.nanpuyue.com/2018/047.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

使用 nginx-rtmp-module 接收 rtmp 流,然后同时推送到多个直播平台,同时使用 lua-nginx-module 来做简单的身份验证。

安装必须的 nginx 模块

debian 9 用户可以直接使用 apt 安装,需启用 stretch-backports 源:

sudo apt install libnginx-mod-rtmp libnginx-mod-http-lua -t stretch-backports

nginx 配置

Gist: nginx.conf

# file: nginx.conf
# date: 2018-10-13
# license: GPLv3 https://www.gnu.org/licenses/gpl-3.0.txt
# author: nanpuyue <[email protected]> https://blog.nanpuyue.com

user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    worker_connections 768;
}

rtmp {
    server{
        listen 1935;
        chunk_size 10240;

        application live {
            live on;
            record off;
            on_publish http://127.0.0.1:2080/auth;
            push rtmp://live.twitch.tv/app/xxxxxxxxxx;
            push rtmp://a.rtmp.youtube.com/xxxxxxxxxx;
        }
    }
}  

http {
    server {
        listen 127.0.0.1:2080;
        location /auth {
            rewrite_by_lua '
                ngx.req.read_body()
                local name = ngx.req.get_post_args().name
                if (name == "xxxxxxxxxx") then
                    ngx.status = 200
                    ngx.say("OK")
                    ngx.exit(200)
                else
                    ngx.status = 403
                    ngx.say("Forbidden")
                    ngx.exit(403)
                end
            ';
        }
    }
}

注意上面有三个 xxxxxxxxxx 是需要自己替换的,push 后面的是推流地址,替换成自己的,也可以自己再添加其他平台的;最后一个 xxxxxxxxxx 是我们想 nginx 推流时要使用的“流名称”,自己生成一个就好,推荐使用 uuidgen 生成一个 UUID。

检查身份验证

启动 nginx 服务后,在服务器上执行下面的命令:

curl -0 http://127.0.0.1:2080/auth -d "name=xxxxxxxxxx"

xxxxxxxxxx 替换成前面生成的 UUID,应该输出 OK,再把 xxxxxxxxxx 换成一个错误的,应该输出 Forbidden。

如果身份验证没有问题,我们就可以使用 obs 来推流了。

在 obs 设置中选择“自定义流媒体服务器”,URL 填入 rtmp://xx.xx.xx.xx/live (xx.xx.xx.xx 是推流服务器的 ip 或域名), 流名称填入我们前面生成的 UUID。

设置好后单击 obs 上的“开始推流”,不出意外的话就可以同时向我们设置的平台推流了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK