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

如何为同域远程服务器文件实现分权限限速下载?

实现分权限的文件下载限速方案

需求与问题

需要实现文件下载限速功能,并且能根据用户权限配置不同的下载速度。此前找到一段适用于本地存储文件的PHP限速代码,但文件实际存储在与当前服务器同主域不同子域的远程服务器上,该代码无法直接适配。若通过远程服务器的httpd/apache2配置全局限速,又无法区分用户权限设置差异化速度。

原本地文件PHP限速代码

<?php
set_time_limit(0);

// 需要发送给客户端的本地文件
$local_file = 'https://remoteserver.com/example.mp4';
// 用户看到的默认文件名
$download_file = 'https://remoteserver.com/example.mp4';

// 设置下载速率限制(=> 1024 kb/s)
$download_rate = 1024; 
if(file_exists($local_file) && is_file($local_file)) {
    // 发送响应头
    header('Cache-control: private');
    header('Content-Type: application/octet-stream'); 
    header('Content-Length: '.filesize($local_file));
    header('Content-Disposition: filename='.$download_file);

    // 刷新内容
    flush();    
    // 打开文件流
    $file = fopen($local_file, "r");    
    while(!feof($file)) {

        // 向浏览器发送当前文件片段
        print fread($file, round($download_rate * 1024));    

        // 刷新浏览器内容
        flush();

        // 休眠1秒
        sleep(1);    
    }    

    // 关闭文件流
    fclose($file);}
else {
    die('Error: The file '.$local_file.' does not exist!');
}

if ($dl) {
} else {
    header('HTTP/1.0 503 Service Unavailable');
    die('Abort, you reached your download limit for this file.');
}
?>

最终解决方案

1. 远程服务器Apache路径限速配置

在远程服务器的httpd/apache2配置中,针对指定URL路径设置不同的限速规则,例如为https://remoteserver.com/slow/...和https://remoteserver.com/fast/...分别配置低速和高速限制:

<Location "/slow">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  5120
    SetEnv rate-initial-burst 5120
</Location>

<Location "/fast">
    SetOutputFilter RATE_LIMIT
    SetEnv rate-limit  204800
    SetEnv rate-initial-burst 204800
</Location>

2. .htaccess URL重写规则

通过.htaccess的重写规则,无需改动现有文件结构即可适配上述限速路径:

RewriteEngine On
RewriteRule ^/?(?:slow|fast)(/downloads/.+)$ $1 [L,NC]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 20:16:07