以下是一个简单的 php nginx 伪静态实现 m3u8 防盗代码的示例:

# nginx 配置
location ~* \.(m3u8)$ {
    if ($http_referer !~* "^https?://(www\.)?example.com/") {
        return 403;
    }
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Expose-Headers' 'Content-Length';
    add_header 'Access-Control-Allow-Methods' 'GET, HEAD, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Range';
    try_files $uri /index.php?$query_string;
}

location ~* \.(ts)$ {
    if ($http_referer !~* "^https?://(www\.)?example.com/") {
        return 403;
    }
    add_header 'Access-Control-Allow-Origin' '*' always;
    add_header 'Access-Control-Expose-Headers' 'Content-Length';
    add_header 'Access-Control-Allow-Methods' 'GET, HEAD, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Range';
    try_files $uri /index.php?$query_string;
}
// index.php
if (isset($_SERVER['HTTP_RANGE'])) {
    // 处理 Range 请求头
    $range = explode('-', $_SERVER['HTTP_RANGE']);
    $start = intval($range[0]);
    $end = isset($range[1]) ? intval($range[1]) : 0;
} else {
    $start = 0;
    $end = 0;
}

$file = '/path/to/videos/' . $_SERVER['REQUEST_URI'];
$filesize = filesize($file);

header('Content-Type: video/mp2t');
header('Content-Length: ' . ($end > 0 ? ($end - $start + 1) : $filesize));
header('Content-Range: bytes ' . $start . '-' . ($end > 0 ? $end : ($filesize - 1)) . '/' . $filesize);
header('Accept-Ranges: bytes');
header('Cache-Control: no-cache');

$handle = fopen($file, 'rb');
fseek($handle, $start);
while (!feof($handle) && ($pos = ftell($handle)) <= ($end > 0 ? $end : ($filesize - 1))) {
    echo fread($handle, min(1024 * 16, ($end > 0 ? ($end - $pos + 1) : ($filesize - $pos + 1))));
    flush();
}
fclose($handle);

以上代码实现了以下功能:

  1. 拦截非法请求,只允许来自 example.com 的请求;
  2. 处理 Range 请求头,实现分段下载;
  3. 发送视频文件的头部和数据块,实现视频播放。

需要注意的是,以上代码只是一个示例,实际使用时需要根据具体情况进行修改和优化

php nginx伪静态实现m3u8防盗代码

原文地址: https://www.cveoy.top/t/topic/fH6t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录