盜鏈消耗帶寬、竊取資源、污染統計。本文系統講解 **Referer 檢查、Token 一次性下載鏈接、簽名 URL 時效性、對象存儲預簽名** 四層防護體系,並提供可直接集成的 PHP 實現代碼。
<?php
// 通用 Referer 白名單中間件
function checkReferer(array $allowedDomains): bool
{
$referer = $_SERVER['HTTP_REFERER'] ?? '';
if ($referer === '') return false; // 無 Referer 直接攔截(或按業務放行)
$parsed = parse_url($referer);
$host = $parsed['host'] ?? '';
// 支援通配符 *.example.com
foreach ($allowedDomains as $domain) {
$pattern = '/^' . str_replace('\*', '.*', preg_quote($domain, '/')) . '$/i';
if (preg_match($pattern, $host)) return true;
}
return false;
}
// 使用示例(下載接口入口)
$allowed = ['example.com', '*.example.com', 'partner-site.com'];
if (!checkReferer($allowed)) {
http_response_code(403);
exit('非法請求來源');
}
?>
缺點:Referer 可偽造、隱私模式/安全軟件會清空、HTTPS→HTTP 不發送 Referer。僅作為第一道防線。
原理:生成帶隨機 Token、過期時間、用戶綁定的下載 URL,驗證後立即銷毀 Token,實現「一鏈一用、時效性、綁定用戶」。
dl:token:{token},TTL=有效期)。/download.php?token=abc123...download.php 驗證 Token 合法性、未過期、未使用 → 標記已用/刪除 Token → 讀取文件流輸出(X-Sendfile 或 readfile)。<?php
// 生成下載 Token(下載頁調用)
function generateDownloadToken(int $fileId, int $userId, int $ttl = 300): string
{
$redis = new Redis(); $redis->connect('127.0.0.1', 6379);
$token = bin2hex(random_bytes(16)); // 32 字符隨機串
$data = json_encode([
'file_id' => $fileId,
'user_id' => $userId,
'created' => time(),
'expire' => time() + $ttl,
'used' => false,
]);
$redis->setex("dl:token:$token", $ttl, $data);
return $token;
}
// download.php 核心邏輯
$token = $_GET['token'] ?? '';
if (!$token) { http_response_code(400); exit('Token 缺失'); }
$redis = new Redis(); $redis->connect('127.0.0.1', 6379);
$key = "dl:token:$token";
$dataJson = $redis->get($key);
if (!$dataJson) { http_response_code(403); exit('鏈接無效或已過期'); }
$data = json_decode($dataJson, true);
if ($data['used']) { http_response_code(403); exit('鏈接已被使用'); }
if ($data['user_id'] !== ($currentUserId ?? 0)) { http_response_code(403); exit('用戶不匹配'); }
// 標記已用(防止併發重複下載)
$redis->del($key); // 或 set used=true 保留審計
// 獲取文件信息(從數據庫)
$file = getFileById($data['file_id']); // ['path'=>'/data/files/xxx.zip', 'name'=>'xxx.zip', 'size'=>123456, 'mime'=>'application/zip']
if (!$file || !file_exists($file['path'])) { http_response_code(404); exit('文件不存在'); }
// 輸出文件流(支援斷點續傳、大文件不佔內存)
sendFile($file['path'], $file['name'], $file['mime']);
function sendFile(string $path, string $filename, string $mime = 'application/octet-stream'): void
{
// 支援 X-Sendfile (Nginx/Apache 模塊) —— 最佳性能,由 Web 服務器直接發送文件
if (function_exists('apache_request_headers') || php_sapi_name() === 'fpm-fcgi') {
// Nginx: location /protected/ { internal; alias /data/files/; }
// Apache: XSendFile on
header("X-Accel-Redirect: /protected/" . basename($path)); // Nginx
// header("X-Sendfile: $path"); // Apache
header("Content-Type: $mime");
header("Content-Disposition: attachment; filename*=UTF-8''" . rawurlencode($filename));
exit;
}
// PHP 直接讀取輸出(無 X-Sendfile 環境)
$fileSize = filesize($path);
header('Content-Type: ' . $mime);
header('Content-Disposition: attachment; filename*=UTF-8\'\'' . rawurlencode($filename));
header('Content-Length: ' . $fileSize);
header('Accept-Ranges: bytes');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
// 斷點續傳支援
if (isset($_SERVER['HTTP_RANGE'])) {
list($range) = explode('-', substr($_SERVER['HTTP_RANGE'], 6));
$start = (int)$range;
$end = $fileSize - 1;
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $start-$end/$fileSize");
header("Content-Length: " . ($end - $start + 1));
} else {
$start = 0;
}
$fp = fopen($path, 'rb');
fseek($fp, $start);
$buffer = 1024 * 8;
while (!feof($fp) && connection_status() === 0) {
echo fread($fp, $buffer);
@ob_flush(); @flush();
}
fclose($fp);
exit;
}
?>
原理:URL 參數包含 expire、signature(HMAC-SHA256),服務端驗證簽名與過期時間,無需存儲狀態。
<?php
const SIGN_SECRET = 'your-32-byte-secret-key================================'; // 32 字節
function generateSignedUrl(string $filePath, int $expireSeconds = 3600): string
{
$expire = time() + $expireSeconds;
$data = $filePath . '|' . $expire;
$signature = hash_hmac('sha256', $data, SIGN_SECRET, true);
$signatureB64 = rtrim(strtr(base64_encode($signature), '+/', '-_'), '='); // URL-safe Base64
return "/download-signed.php?file=" . rawurlencode($filePath) . "&expire=$expire&sign=$signatureB64";
}
function verifySignedUrl(string $filePath, int $expire, string $signatureB64): bool
{
if (time() > $expire) return false;
$data = $filePath . '|' . $expire;
$expected = hash_hmac('sha256', $data, SIGN_SECRET, true);
$expectedB64 = rtrim(strtr(base64_encode($expected), '+/', '-_'), '=');
return hash_equals($expectedB64, $signatureB64); // 時序安全比較
}
// download-signed.php
$file = $_GET['file'] ?? '';
$expire = (int)($_GET['expire'] ?? 0);
$sign = $_GET['sign'] ?? '';
if (!$file || !$expire || !$sign) { http_response_code(400); exit('參數缺失'); }
// 防止目錄遍歷
$file = realpath('/data/files/' . $file);
if (!$file || !str_starts_with($file, realpath('/data/files/'))) { http_response_code(403); exit('非法路徑'); }
if (!verifySignedUrl($file, $expire, $sign)) { http_response_code(403); exit('簽名無效或已過期'); }
sendFile($file, basename($file));
?>
文件存儲於 AWS S3 / 阿里云 OSS / 騰訊云 COS / 七牛云等,直接使用 SDK 生成預簽名 URL,**完全卸載帶寬到 CDN/對象存儲**,應用服務器零流量轉發。
<?php
// 阿里云 OSS 示例
use OSS\OssClient;
use OSS\Core\OssException;
$oss = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$bucket = 'my-bucket';
$object = 'downloads/report-2024.pdf';
// 生成預簽名 URL(有效期 1 小時,允許 GET)
$signedUrl = $oss->signUrl($bucket, $object, 3600, 'GET');
// 返回: https://my-bucket.oss-cn-hangzhou.aliyuncs.com/downloads/report-2024.pdf?OSSAccessKeyId=...&Expires=...&Signature=...
// 前端直接跳轉或 下載
// 簽名由 OSS 服務端驗證,應用服務器無流量壓力
?>
用戶請求下載頁
│
▼
┌─────────────────────────────────────┐
│ 1. Referer 白名單檢查 (WAF/中間件) │ ← 低成本攔截 80% 盜鏈
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ 2. 生成一次性 Token / 簽名 URL │ ← 核心業務邏輯控制
│ - 綁定用戶/設備/IP │
│ - 短時效 (5-30 分鐘) │
│ - 一次性失效 │
└─────────────────────────────────────┘
│
▼
┌─────────────────────────────────────┐
│ 3. 下載接口驗證 Token/簽名 │
│ - 刪除 Token / 驗證 HMAC │
│ - X-Sendfile / 對象存儲預簽名 │
│ - 斷點續傳、限速 │
└─────────────────────────────────────┘
│
▼
文件流輸出 → 用戶