功能需求
- HTTP 302/301 重定向 (首選,SEO 友善)
- Meta Refresh 降級 (Header 已送出時)
- JavaScript 降級 (Meta 不支援時)
- 倒數計時、自訂訊息、樣式美化
完整工具函數
<?php
/**
* 頁面轉向
* @param string $url 目標 URL
* @param string $message 提示訊息
* @param int $seconds 延遲秒數
* @param int $httpCode 301/302/303/307
* @return never
*/
function redirect(string $url, string $message = '正在跳轉...', int $seconds = 3, int $httpCode = 302): never {
// 1. 嘗試 HTTP Header 重定向 (最快、SEO 最佳)
if (!headers_sent()) {
if ($httpCode !== 302) {
http_response_code($httpCode);
}
header("Location: $url", true, $httpCode);
exit;
}
// 2. Header 已送出,降級 Meta Refresh
// 確保輸出緩衝已關閉或已刷新
if (ob_get_level()) {
ob_end_flush();
}
// 防 XSS
$safeUrl = htmlspecialchars($url, ENT_QUOTES, 'UTF-8');
$safeMsg = htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
$safeSeconds = (int)$seconds;
// 輸出完整 HTML 頁面
echo '<!DOCTYPE html>';
echo '<html><head><meta charset="UTF-8">';
echo "<title>$safeMsg</title>";
echo "<meta http-equiv=\"refresh\" content=\"$safeSeconds;url=$safeUrl\">";
echo '<style>
body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f5f5f5}
.box{background:white;padding:2rem;border-radius:8px;box-shadow:0 2px 10px rgba(0,0,0,.1);text-align:center;max-width:400px}
.spinner{border:3px solid #e3e3e3;border-top:3px solid #3498db;border-radius:50%;width:40px;height:40px;animation:spin 1s linear infinite;margin:0 auto 1rem}
@keyframes spin{to{transform:rotate(360deg)}}
a{color:#3498db;text-decoration:none}
</style>';
echo '</head><body><div class="box">';
echo '<div class="spinner"></div>';
echo "<p>$safeMsg</p>";
echo "<p><a href=\"$safeUrl\">如果瀏覽器未自動跳轉,請點這裡</a></p>";
echo '</div></body></html>';
exit;
}
// 使用範例
// redirect('/dashboard', '登入成功,跳轉至儀表板...', 2, 302);
// redirect('https://new-site.com', '網站已搬家', 5, 301);
進階:AJAX 請求專用回應
function redirectAjax(string $url, string $message = '', int $code = 200): never {
header('Content-Type: application/json; charset=UTF-8');
http_response_code($code);
echo json_encode([
'redirect' => $url,
'message' => $message,
'code' => $code
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
}
// 前端處理
// fetch('/login', {method:'POST', body:...})
// .then(r => r.json())
// .then(d => { if(d.redirect) window.location.href = d.redirect; })
常見錯誤避坑
| 錯誤寫法 | 問題 | 正確寫法 |
header("Location: $url"); 無 exit | 腳本繼續執行,可能輸出內容干擾 | 加 exit; |
相對路徑 Location: page.php | RFC 7231 要求絕對 URI | 用 $scheme://$host$path 組裝絕對 URL |
| 中文 URL 未編碼 | 瀏覽器解析異常 | header('Location: ' . urlencode($url)) (僅路徑部分需編碼) |
| 大量輸出後才 redirect | headers_sent() 為 true,Header 失效 | 前置檢查或全程 ob_start() |
SEO 重定向最佳實踐
- 301 永久移動:網域遷移、URL 結構永久變更、HTTP→HTTPS、www↔非 www 規範化
- 302 暫時移動:登入後跳轉、A/B 測試、維護頁面
- 303 See Other:POST 請求成功後導向 GET 頁面 (PRG 模式)
- 307 Temporary Redirect:保持原請求方法 (POST→POST)
- 避免重定向鏈 (A→B→C),直接指向最終目標
- 更新 Sitemap、內部連結、Canonical 標籤