Meta Refresh 與 JavaScript 重新導向教學
伺服器端重新導向(301/302)永遠是正確的首選。但有時您無法存取伺服器設定,或需要根據執行時條件進行重新導向 — 這時客戶端重新導向就派上用場了。
HTML meta refresh
<!-- 立即重新導向 -->
<meta http-equiv="refresh" content="0; url=/new-page.html">
<!-- 3 秒後重新導向 -->
<meta http-equiv="refresh" content="3; url=https://newdomain.com">
- ✅ 不需要 JavaScript 即可運作
- ✅ 只需一行 HTML
- ❌ 頁面載入後無法取消
- ❌ 造成返回鍵陷阱(頁面在返回時再次重新導向)
- ❌ 對 SEO 不利 — Google 不建議使用
⚠️ 返回鍵陷阱
Meta refresh 在重新導向前會將當前頁面加入瀏覽器歷史記錄。當使用者按下返回鍵時,會回到重新導向頁面並立即被再次導向。請盡可能避免這種模式。
JavaScript 重新導向方法
window.location.href(最常用)
// 將當前頁面加入歷史記錄 — 使用者可以返回
window.location.href = 'https://example.com';
location.replace()(不留歷史記錄)
// 取代當前歷史記錄項目 — 使用者無法返回
location.replace('https://example.com');
location.assign()(與 href 相同)
location.assign('https://example.com');
window.open()(新分頁)
window.open('https://example.com', '_blank');
主要差異
歷史記錄
- 會加入歷史記錄:
location.href、location.assign()、meta refresh - 不會加入歷史記錄:
location.replace()
可否取消
- 可以取消:JavaScript(使用
clearTimeout) - 無法取消:meta refresh
何時使用各種方式
使用 meta refresh 的時機
- 您有一個沒有 JavaScript 的靜態 HTML 頁面
- 需要一個帶倒數計時的「頁面已移動」通知
使用 location.href 的時機
- 需要條件式重新導向邏輯
- 希望使用者能夠返回
if (!user.isLoggedIn) {
location.href = '/login';
}
使用 location.replace() 的時機
- 登入後 — 不讓使用者返回登入頁面
- 錯誤頁面自動重新導向
- 行動/桌面裝置偵測重新導向
if (/Android|iPhone/i.test(navigator.userAgent)) {
location.replace('/mobile/');
}
SEO 影響
- Meta refresh — Google 官方不建議使用;可能導致排名下降
- JavaScript 重新導向 — Google 可以處理,但比伺服器端重新導向慢
- 兩者都不帶 HTTP 狀態碼 — 搜尋引擎無法判斷移動是永久的還是暫時的
🚨 重要
任何永久的網址變更,請務必使用伺服器端 301 重新導向。客戶端重新導向僅適用於動態的執行時場景。
常見陷阱
重新導向後的程式碼仍會執行
// ❌ 下方的程式碼仍然會執行
if (needRedirect) { location.href = '/other'; }
doSomethingElse(); // 仍然會執行!
// ✅ 使用 return
if (needRedirect) { location.href = '/other'; return; }
doSomethingElse();
行動裝置重新導向迴圈
// ✅ 防止重複重新導向
if (isMobile && !location.pathname.startsWith('/mobile/')) {
location.replace('/mobile' + location.pathname);
}
查詢字串遺失
// ❌ 查詢字串被丟棄
location.href = '/new-page';
// ✅ 保留查詢字串
location.href = '/new-page' + location.search;