php nginx实现直播
PHP与Nginx实现直播方案
直播功能通常需要结合流媒体服务器、前端播放器和后端处理逻辑。PHP主要用于后端逻辑处理,Nginx可作为Web服务器或与RTMP模块结合作为流媒体服务器。
使用Nginx RTMP模块搭建流媒体服务器
安装Nginx并添加RTMP模块:
# 下载Nginx和RTMP模块源码
wget http://nginx.org/download/nginx-1.25.3.tar.gz
wget https://github.com/arut/nginx-rtmp-module/archive/master.zip
# 解压并编译安装
tar -zxvf nginx-1.25.3.tar.gz
unzip master.zip
cd nginx-1.25.3
./configure --add-module=../nginx-rtmp-module-master
make && make install
配置Nginx RTMP(在nginx.conf中添加):
rtmp {
server {
listen 1935;
chunk_size 4096;
application live {
live on;
record off;
allow publish 127.0.0.1;
deny publish all;
}
}
}
PHP处理直播推流鉴权
创建推流鉴权接口(PHP示例):

<?php
$stream_key = $_GET['key'];
$allowed_keys = ['secret_key_123'];
if (!in_array($stream_key, $allowed_keys)) {
header('HTTP/1.1 403 Forbidden');
exit;
}
// 返回推流地址
$rtmp_url = "rtmp://your-server-ip/live/".uniqid();
echo json_encode(['url' => $rtmp_url]);
?>
前端播放器集成
使用HTML5播放器播放直播流:
<video id="player" controls autoplay></video>
<script src="https://cdn.jsdelivr.net/npm/hls.js@latest"></script>
<script>
if(Hls.isSupported()) {
var video = document.getElementById('player');
var hls = new Hls();
hls.loadSource('http://your-server-ip/hls/stream.m3u8');
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED,function() {
video.play();
});
}
</script>
Nginx配置HLS输出
在RTMP配置中添加HLS支持:

rtmp {
server {
application live {
hls on;
hls_path /tmp/hls;
hls_fragment 3s;
hls_playlist_length 60s;
}
}
}
http {
server {
location /hls {
types {
application/vnd.apple.mpegurl m3u8;
video/mp2t ts;
}
root /tmp;
add_header Cache-Control no-cache;
}
}
}
推流客户端设置
使用OBS或其他推流软件配置:
- 服务器:rtmp://your-server-ip/live
- 流密钥:secret_key_123
安全增强措施
限制推流IP并启用HTTPS:
http {
server {
listen 443 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location /auth {
proxy_pass http://localhost/auth.php;
}
}
}
性能优化建议
启用Nginx缓存和Gzip压缩:
http {
gzip on;
gzip_types text/plain application/xml;
proxy_cache_path /tmp/nginx levels=1:2 keys_zone=my_cache:10m inactive=60m;
}
以上方案实现了基本的直播功能架构,可根据实际需求扩展用户认证、弹幕互动、录制回放等功能。注意服务器需要足够的带宽资源支持直播流量。






