You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Nginx的MP4文件GET参数权限验证需求咨询

实现MP4文件带密钥访问的Nginx+PHP方案

刚好前段时间帮朋友配置过类似的需求,完美匹配你的场景——禁止直接访问MP4文件夹,必须携带指定GET参数才能通过PHP验证权限后访问。下面是完整的配置步骤:

一、Nginx配置部分

首先在你的Nginx server块中添加以下配置,核心是拦截MP4文件请求、校验参数存在性,并转发给PHP脚本处理:

server {
    # 你的其他server配置(比如listen、server_name等)
    
    # 处理MP4文件的访问请求
    location /MP4files/ {
        autoindex off; # 彻底关闭目录索引,防止用户枚举文件
        charset utf-8;

        # 检查请求是否携带Secretkey参数,无参数直接返回403
        if ($arg_Secretkey = "") {
            return 403 "Secret key is required";
        }

        # 将请求重写至PHP验证脚本,传递文件名和密钥参数
        rewrite ^/MP4files/(.*\.mp4)$ /auth_check.php?file=$1&Secretkey=$arg_Secretkey last;
    }

    # 内部访问专用的MP4文件路径(禁止外部直接访问)
    location /internal_mp4/ {
        internal; # 关键:只允许Nginx内部重定向访问,外部请求直接404
        alias /your/real/server/path/MP4files/; # 替换为你服务器上MP4文件夹的绝对路径
        add_header Content-Type video/mp4;
    }

    # 确保PHP脚本能正常执行(如果已有PHP配置可忽略)
    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock; # 替换为你的PHP-FPM路径
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

二、PHP权限验证脚本(auth_check.php)

在网站根目录创建auth_check.php,负责验证密钥合法性、安全校验文件名,并通过Nginx的X-Accel-Redirect高效返回文件(比PHP直接输出文件性能好很多):

<?php
// 1. 获取并过滤请求参数
$secretKey = trim($_GET['Secretkey'] ?? '');
$fileName = trim($_GET['file'] ?? '');

// 2. 安全防护:防止路径遍历攻击(必须做!)
if (strpos($fileName, '..') !== false 
    || !preg_match('/^[a-zA-Z0-9_\-]+\.mp4$/i', $fileName)) {
    http_response_code(403);
    exit('Invalid file request');
}

// 3. 权限验证逻辑(这里替换成你的实际验证规则)
// 示例:固定密钥验证,实际可改为从数据库/缓存读取有效密钥、校验时效等
$validSecretKeys = ['dancingbear', 'anothervalidkey']; // 可扩展为动态获取
if (!in_array($secretKey, $validSecretKeys)) {
    http_response_code(403);
    exit('Invalid or expired secret key');
}

// 4. 验证通过,让Nginx直接返回文件
$internalFilePath = '/internal_mp4/' . $fileName;
// 可选:检查文件是否存在
$realFilePath = '/your/real/server/path/MP4files/' . $fileName;
if (!file_exists($realFilePath)) {
    http_response_code(404);
    exit('File not found');
}

// 发送X-Accel-Redirect头,让Nginx处理文件输出
header('X-Accel-Redirect: ' . $internalFilePath);
header('Content-Type: video/mp4');
exit;

三、关键注意事项

  • 路径配置:务必替换配置中的/your/real/server/path/MP4files/为你服务器上MP4文件夹的真实绝对路径,否则会出现404或权限错误。
  • 安全校验:PHP中的路径遍历防护不能省略,避免攻击者通过构造../路径访问服务器上的其他文件。
  • 性能优化:使用X-Accel-Redirect而非PHP直接readfile()输出文件,能大幅提升大文件的访问性能,因为Nginx在静态文件处理上比PHP高效得多。
  • 密钥管理:如果是生产环境,建议不要把密钥硬编码在PHP里,可存在数据库、环境变量或配置文件中,支持动态更新。

测试的时候直接访问http://www.blabla.com/MP4files/dance.mp4?Secretkey=dancingbear就能验证是否生效啦~

内容的提问来源于stack exchange,提问作者Siy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:53:12