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">

⚠️ 返回鍵陷阱

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');

主要差異

歷史記錄

可否取消

何時使用各種方式

使用 meta refresh 的時機

使用 location.href 的時機

if (!user.isLoggedIn) {
    location.href = '/login';
}

使用 location.replace() 的時機

if (/Android|iPhone/i.test(navigator.userAgent)) {
    location.replace('/mobile/');
}

SEO 影響

🚨 重要

任何永久的網址變更,請務必使用伺服器端 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;