<?php
// 簡單版:直接跳轉
$url = $_GET['url'] ?? '';
if ($url) {
// 安全:補全協定,防止開放重導向
if (!preg_match('#^https?://#i', $url)) {
$url = 'https://' . $url;
}
header("Location: $url", true, 302);
exit;
}
// 顯示輸入表單...
?>
開放重導向是 OWASP Top 10 風險,攻擊者可構造 site.com/redirect?url=evil.com/phishing 誘騙用戶。必須實施白名單校驗:
<?php
class SafeRedirect
{
private array $allowedHosts = [
'example.com',
'api.example.com',
'partner.com',
];
private array $allowedPaths = [
'/login',
'/callback',
'/dashboard',
];
public function redirect(string $target, int $statusCode = 302): never
{
$parsed = parse_url($target);
if (!$parsed || !isset($parsed['host'])) {
$this->fail('無效 URL 格式');
}
$host = strtolower($parsed['host']);
$path = $parsed['path'] ?? '/';
// 精確主機匹配 (含子域名需顯式列出)
if (!in_array($host, $this->allowedHosts, true)) {
$this->fail("主機 $host 不在白名單中");
}
// 可選:路徑前綴檢查
$pathOk = false;
foreach ($this->allowedPaths as $allowed) {
if (str_starts_with($path, $allowed)) {
$pathOk = true;
break;
}
}
if (!$pathOk) {
$this->fail("路徑 $path 不在允許範圍");
}
// 防止頭部注入
$safeUrl = filter_var($target, FILTER_VALIDATE_URL);
if (!$safeUrl) {
$this->fail('URL 過濾失敗');
}
header("Location: $safeUrl", true, $statusCode);
exit;
}
private function fail(string $msg): never
{
http_response_code(400);
error_log("安全重導向攔截: $msg | Target: " . ($_GET['url'] ?? 'unknown'));
die("跳轉被攔截:$msg");
}
}
// 使用
$redirector = new SafeRedirect();
$redirector->redirect($_GET['url'] ?? '');
<!DOCTYPE html>
<html><head><title>安全跳轉頁</title></head><body>
<form method="get">
<label>目標網址 (需在白名單中):
<input type="url" name="url" placeholder="https://example.com/path" required />
</label>
<button type="submit">跳轉</button>
</form>
</body></html>
| 碼 | 語義 | 適用場景 |
|---|---|---|
| 301 | Moved Permanently | 永久遷移,SEO 權重傳遞,瀏覽器緩存 |
| 302 | Found (暫時移動) | 預設、臨時跳轉,不傳遞 SEO 權重 |
| 303 | See Other | POST 請求後導向 GET 頁面 (PRG 模式) |
| 307 | Temporary Redirect | 保持原請求方法 (POST→POST),HTTP/1.1 |
| 308 | Permanent Redirect | 永久且保持方法,HTTP/1.1 |
<?php if (headers_sent()): ?>
<script>
// 延遲 0 確保 DOM 就緒
setTimeout(() => window.location.replace('= htmlspecialchars($url, ENT_QUOTES) ?>'), 0);
</script>
<noscript><meta http-equiv="refresh" content="0;url== htmlspecialchars($url) ?>"></noscript>
<p>正在跳轉... <a href="= htmlspecialchars($url) ?>">點此手動跳轉</a></p>
<?php endif; ?>
核心原則:永不信任用戶輸入的 URL,白名單驗證 + 協定補全 + 頭部注入防護 + 適當狀態碼。