插件窝 干货文章 Mac上怎么搭建nginx+rtmp直播服务器

Mac上怎么搭建nginx+rtmp直播服务器

Nginx bash 配置 RTMP 660    来源:    2025-04-25

Mac上搭建Nginx+RTMP直播服务器指南

准备工作

  1. 确保你的Mac已安装Homebrew(如果没有,先安装) bash /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

安装Nginx with RTMP模块

  1. 使用Homebrew安装带RTMP模块的Nginx

    brew tap denji/nginx
    brew install nginx-full --with-rtmp-module
    
  2. 安装完成后,查看Nginx信息

    brew info nginx-full
    

配置Nginx

  1. 编辑Nginx配置文件

    sudo nano /usr/local/etc/nginx/nginx.conf
    
  2. 在配置文件中添加RTMP配置(在http块之外添加):

    rtmp {
       server {
           listen 1935;
           chunk_size 4096;
           allow publish 127.0.0.1;
           deny publish all;
    
           application live {
               live on;
               record off;
               # 推流鉴权(可选)
               # on_publish http://localhost/auth;
           }
       }
    }
    
  3. 保存后检查配置是否正确

    sudo nginx -t
    

启动Nginx服务

  1. 启动Nginx

    sudo nginx
    
  2. 检查Nginx是否运行

    ps aux | grep nginx
    
  3. 如果需要停止或重启Nginx:

    sudo nginx -s stop    # 停止
    sudo nginx -s reload  # 重新加载配置
    

测试直播流

  1. 使用OBS或其他推流软件进行测试

    • 服务器地址: rtmp://localhost/live
    • 流密钥: 任意设置(如test)
  2. 使用VLC或其他播放器观看

    • 打开VLC,选择"媒体" > "打开网络串流"
    • 输入地址: rtmp://localhost/live/test

可选配置

启用HLS支持

在RTMP配置中添加:

application live {
    live on;
    record off;
    hls on;
    hls_path /tmp/hls;
    hls_fragment 3;
    hls_playlist_length 60;
}

然后在http块中添加:

server {
    listen 8080;

    location /hls {
        types {
            application/vnd.apple.mpegurl m3u8;
            video/mp2t ts;
        }
        root /tmp;
        add_header Cache-Control no-cache;
    }
}

启用HTTP访问

sudo nano /usr/local/etc/nginx/nginx.conf

找到http部分的server块,确保有以下内容:

server {
    listen       8080;
    server_name  localhost;

    location /stat {
        rtmp_stat all;
        rtmp_stat_stylesheet stat.xsl;
    }

    location /stat.xsl {
        root /usr/local/nginx/html;
    }

    location / {
        root   html;
        index  index.html index.htm;
    }
}

常见问题解决

  1. 端口被占用

    sudo lsof -i :1935
    sudo kill -9 [PID]
    
  2. 权限问题

    sudo chown -R $(whoami) /usr/local/etc/nginx
    
  3. 查看日志

    tail -f /usr/local/var/log/nginx/error.log
    
  4. 更新配置后不生效

    sudo nginx -s reload
    

这样你就成功在Mac上搭建了一个RTMP直播服务器,可以进行直播推流和观看了!