根據查詢字串參數決定導向目標是常見需求(如短網址、多語系導向、A/B 測試)。本文提供安全、可擴充的導向實作方案。
<?php
// redirect.php
$targetMap = [
'baidu' => 'https://www.baidu.com',
'qq' => 'https://www.qq.com',
'hao123' => 'https://www.hao123.com',
'google' => 'https://www.google.com',
];
// 從查詢字串取得 key
$key = $_GET['to'] ?? 'default';
// 驗證並導向
$url = $targetMap[$key] ?? $targetMap['default'] ?? 'https://example.com';
// 安全:確保是有效 URL 且為允許的域名
if (!filter_var($url, FILTER_VALIDATE_URL)) {
$url = 'https://example.com';
}
// 執行導向
header("Location: $url", true, 302);
exit;
?>
<?php
// redirect.php
$allowedDomains = [
'baidu.com',
'qq.com',
'google.com',
'example.com',
];
$rawUrl = $_GET['url'] ?? '';
$url = urldecode($rawUrl);
// 基本格式驗證
if (!filter_var($url, FILTER_VALIDATE_URL)) {
die('無效的 URL 參數');
}
// 解析域名
$parsed = parse_url($url);
$host = $parsed['host'] ?? '';
// 域名白名單檢查 (防開放式重導向攻擊 Open Redirect)
$allowed = false;
foreach ($allowedDomains as $domain) {
if ($host === $domain || str_ends_with($host, '.' . $domain)) {
$allowed = true;
break;
}
}
if (!$allowed) {
die('不允許的導向域名');
}
// 可選:記錄導向日誌
error_log("Redirect: {$_SERVER['REMOTE_ADDR']} -> $url");
header("Location: $url", true, 302);
exit;
?>
Open Redirect 漏洞 允許攻擊者構造惡意連結誘騙使用者:
https://yoursite.com/redirect.php?url=https://evil.com/phishing
防禦措施:
<?php
// redirect_confirm.php
$url = $_GET['url'] ?? '';
$parsed = parse_url($url);
$host = $parsed['host'] ?? '';
if (!$url || !filter_var($url, FILTER_VALIDATE_URL) || !in_array($host, $allowedDomains)) {
die('無效導向');
}
?>
頁面導向確認
<?php
// 根據 Accept-Language 或 GeoIP 導向
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? 'zh-TW', 0, 2);
$map = [
'zh' => '/zh-TW/',
'en' => '/en/',
'ja' => '/ja/',
];
header('Location: ' . ($map[$lang] ?? '/zh-TW/'), true, 302);
exit;
<?php
// short.php
$code = $_GET['code'] ?? '';
$stmt = $pdo->prepare('SELECT original_url FROM short_urls WHERE code = ? AND (expires_at IS NULL OR expires_at > NOW())');
$stmt->execute([$code]);
$url = $stmt->fetchColumn();
if ($url) {
// 記錄點擊
$pdo->prepare('UPDATE short_urls SET clicks = clicks + 1 WHERE code = ?')->execute([$code]);
header("Location: $url", true, 301); // 301 永久導向利於 SEO
exit;
}
http_response_code(404);
echo '短網址不存在或已過期';
<?php
// 根據 Cookie 或隨機分配
$variant = $_COOKIE['ab_test'] ?? (random_int(0, 1) ? 'A' : 'B');
setcookie('ab_test', $variant, time() + 86400 * 30, '/', '', true, true);
$urls = ['A' => '/landing-a.php', 'B' => '/landing-b.php'];
header("Location: {$urls[$variant]}", true, 302);
exit;
| 原則 | 做法 |
|---|---|
| 永遠驗證 URL | `filter_var($url, FILTER_VALIDATE_URL)` |
| 域名白名單 | 陣列/資料庫維護允許域名 |
| 使用代碼而非完整 URL | `?to=baidu` 而非 `?url=https://...` |
| 加上確認頁 | 高風險導向 (外部域名、付費頁) |
| 記錄稽核日誌 | IP、時間、目標 URL、User-Agent |
| 設定正確狀態碼 | 301 永久、302 暫時、307 保持方法 |
| 防止循環導向 | 限制導向鏈長度、檢查 Referer |