插件窝 干货文章 nginx-rtmp-module模块实现视频点播的示例代码

nginx-rtmp-module模块实现视频点播的示例代码

Nginx RTMP videos 配置 709    来源:    2025-04-01

Nginx-RTMP 模块实现视频点播示例

下面是一个完整的 nginx-rtmp-module 实现视频点播(VOD)的配置示例和说明。

1. 安装 Nginx 和 RTMP 模块

首先需要安装带有 RTMP 模块的 Nginx:

# 下载源码
wget http://nginx.org/download/nginx-1.25.3.tar.gz
wget https://github.com/arut/nginx-rtmp-module/archive/refs/tags/v1.2.2.tar.gz

# 解压
tar -zxvf nginx-1.25.3.tar.gz
tar -zxvf v1.2.2.tar.gz

# 编译安装
cd nginx-1.25.3
./configure --add-module=../nginx-rtmp-module-1.2.2
make
sudo make install

2. Nginx 配置示例

编辑 /usr/local/nginx/conf/nginx.conf 文件,添加 RTMP 和 HTTP 配置:

worker_processes  auto;

events {
    worker_connections  1024;
}

# RTMP 服务器配置
rtmp {
    server {
        listen 1935;
        chunk_size 4096;

        # 点播应用配置
        application vod {
            play /var/videos;  # 视频文件存放目录
        }

        # 直播应用配置(可选)
        application live {
            live on;
            record off;
        }
    }
}

# HTTP 服务器配置
http {
    include       mime.types;
    default_type  application/octet-stream;

    server {
        listen       80;
        server_name  localhost;

        # 视频点播 HTTP 访问
        location /vod/ {
            alias /var/videos/;
            autoindex on;
            add_header Access-Control-Allow-Origin *;
        }

        # RTMP 状态页面
        location /stat {
            rtmp_stat all;
            rtmp_stat_stylesheet stat.xsl;
        }

        location /stat.xsl {
            root /path/to/nginx-rtmp-module/;
        }
    }
}

3. 创建视频目录

sudo mkdir -p /var/videos
sudo chmod -R 755 /var/videos

4. 视频文件准备

将视频文件放入 /var/videos 目录,建议使用以下格式: - MP4 (H.264/AAC) - FLV (H.264/AAC) - MPEG-TS

例如:

sudo cp example.mp4 /var/videos/

5. 启动 Nginx

sudo /usr/local/nginx/sbin/nginx

6. 客户端访问方式

使用 RTMP 协议点播

rtmp://服务器IP/vod/example.mp4

使用 HTTP 协议访问

http://服务器IP/vod/example.mp4

7. 高级配置选项

限制访问

application vod {
    play /var/videos;

    # 限制特定IP访问
    allow 192.168.1.0/24;
    deny all;

    # 或使用认证
    on_play http://localhost/auth;
}

HLS 点播

application vod {
    play /var/videos;

    # 启用HLS
    hls on;
    hls_path /tmp/hls;
    hls_fragment 5s;
    hls_playlist_length 30s;
}

多码率支持

application vod {
    play /var/videos;

    # 多码率配置
    exec_static ffmpeg -i /var/videos/$name.mp4
                      -c:v libx264 -c:a aac -b:v 256k -b:a 64k -vf scale=640:360 -f flv rtmp://localhost/hls/$name_low
                      -c:v libx264 -c:a aac -b:v 512k -b:a 128k -vf scale=854:480 -f flv rtmp://localhost/hls/$name_mid
                      -c:v libx264 -c:a aac -b:v 1024k -b:a 192k -f flv rtmp://localhost/hls/$name_hi;
}

8. 常见问题解决

  1. 403 Forbidden 错误

    • 检查视频文件权限:chmod 644 /var/videos/*
    • 检查 Nginx 用户权限:确保 user 指令在 nginx.conf 中设置正确
  2. 无法播放视频

    • 确保视频格式正确(建议使用 H.264/AAC 编码的 MP4)
    • 检查 RTMP 端口 1935 是否开放
  3. 性能问题

    • 增加 worker_processes 数量
    • 调整 worker_connections
    • 考虑使用 CDN 分发视频

以上配置提供了一个完整的视频点播解决方案,可以根据实际需求进行调整和扩展。