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への影響

🚨 重要

恒久的なURL変更には、必ずサーバーサイドの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;