盜鏈指他站直接引用你的資源(圖片、下載檔案、影音、API),消耗你的頻寬與伺服器資源,卻無流量、廣告收入或品牌曝光。防盜鏈核心目標:**驗證請求來源合法性,拒絕非授權存取**。
資源ID + 隨機數 + 密鑰 產生簽名,存入 Session/download.php?id=123&token=abc123readfile() / fpassthru() 串流輸出,**不暴露真實檔案路徑**缺點:Referer 可偽造、部分瀏覽器/防火牆會移除、HTTPS→HTTP 不傳 Referer。
download_page.php $resourceId,
'nonce' => $nonce,
'created' => time(),
'expires' => time() + 300, // 5 分鐘有效
];
// 產生下載連結
$downloadUrl = "/download.php?token=$token";
?>
點擊下載
download.php $tokenData['expires']) {
unset($_SESSION['download_tokens'][$token]);
exit('下載連結已過期,請重新獲取');
}
// 驗證 Referer(防止直接複製連結)
$refererHost = parse_url($_SERVER['HTTP_REFERER'] ?? '', PHP_URL_HOST) ?? '';
$allowed = ['example.com', 'www.example.com'];
if (!in_array($refererHost, $allowed, true)) {
exit('請從官方頁面下載');
}
// 關鍵:一次性使用,驗證通過即銷毀
unset($_SESSION['download_tokens'][$token]);
// 取得真實檔案路徑(資料庫查詢,路徑不可外洩)
$resourceId = $tokenData['resource_id'];
$filePath = getRealFilePath($resourceId); // 自行實作:從 DB 取得絕對路徑
if (!$filePath || !is_file($filePath)) {
exit('檔案不存在');
}
// 串流輸出(支援大檔案、斷點續傳邏輯可自行擴充)
$fileName = basename($filePath);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . rawurlencode($fileName) . '"');
header('Content-Length: ' . filesize($filePath));
header('Accept-Ranges: bytes');
readfile($filePath); // 或 fpassthru(fopen($filePath, 'rb'));
exit;
function getRealFilePath(int $id): ?string {
// 範例:從資料庫查詢
// $pdo->prepare("SELECT file_path FROM resources WHERE id=? AND status=1");
// return $stmt->fetchColumn() ?: null;
return "/var/www/files/protected/resource_{$id}.zip"; // 示意
}
?>
PHP 處理每個請求有開銷。靜態資源建議在 Web Server 層攔截:
location ~* \.(jpg|jpeg|png|gif|webp|pdf|zip|mp4)$ {
valid_referers none blocked example.com www.example.com;
if ($invalid_referer) {
return 403;
}
# 可選:限速、快取、簽名連結 (ngx_http_secure_link_module)
}
# 產生連結邏輯(PHP 端)
# $expire = time() + 3600;
# $secret = 'secret_key';
# $md5 = base64_encode(md5("/protected/$file$expire $secret", true));
# $url = "/protected/$file?md5=$md5&expires=$expire";
location /protected/ {
secure_link $arg_md5,$arg_expires;
secure_link_md5 "secret_key$uri$secure_link_expires";
if ($secure_link = "") { return 403; }
if ($secure_link = "0") { return 410; } # 過期
# 通過
}
| 策略 | 適用場景 | 實作要點 |
|---|---|---|
| 圖片浮水印 | 內容型網站 | GD/Imagick 疊加 Logo,盜鏈即幫你宣傳 |
| IIS ISAPI_Rewrite | Windows 主機 | 類似 Apache mod_rewrite 規則 |
| CDN 防盜鏈 | 雲端部署 | Cloudflare/AWS CloudFront/騰訊雲 CDN 控制台直接設定 Referer 白名單、簽名鑑權 |
| User-Agent 過濾 | 阻擋爬蟲 | 配合 IP 限流、行為分析(非萬靈丹) |
防盜鏈無絕對方案,**分層防禦**最穩健:
根據資源類型(靜態/動態)、價值(公開/付費)、架構(PHP/Nginx/CDN)選擇適當組合。