この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:7
ページ更新者:guest
更新日時:2026-06-11 07:07:02

タイトル: リダイレクト(header)
SEOタイトル: PHP リダイレクト (header Location) 完全ガイド(301/302/303/307/308 / exit / 出力前必須)

この本文には実行可能なタグ等が含まれるため、安全のためHTMLソースとして表示しています。本文データは変更していません。

<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;background:#fffbea;border:1px solid #f4c430;margin:1em 0;width:100%"><tr><td style="background:#f4c430;color:#000;font-weight:bold;padding:8px">この記事の要点</td></tr><tr><td style="padding:10px"><ul><li><strong><code>header("Location: /path"); exit;</code></strong> が PHP リダイレクトの基本形</li><li><strong>必ず <code>exit;</code></strong> を付ける。後続コードが実行されてしまうとセキュリティ事故に</li><li><strong>HTTP ステータスを意識</strong>: 301 (恒久) / 302 (一時) / 303 (POST 後 GET) / 307 (一時、メソッド保持) / 308 (恒久、メソッド保持)</li><li><strong>出力前に呼ぶ</strong> — 1 行でも echo / 空白 / BOM があると <code>Cannot modify header information</code> エラー</li><li>出力バッファ (<code>ob_start()</code>) で回避できるが、根本対策は<strong>出力前に header() を呼ぶ</strong></li><li>Laravel なら <code>return redirect()->route("home");</code> でフレームワーク管理</li></ul></td></tr></table>
<h2>基本構文</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php"><?php
// 最小形 (デフォルト 302 Found)
header(&apos;Location: /thanks.php&apos;);
exit;</code></pre>
<p><strong>必ず <code>exit;</code> (または <code>die;</code>) を付けてください。</strong> Location ヘッダーを送ってもブラウザがリダイレクトする前に、PHP は残りのコードを最後まで実行します。認証チェックの直後でリダイレクトしているつもりが、続けて機密処理を実行してしまう事故が頻発します。</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php">// ❌ 危険: リダイレクト後に処理が継続する
if (!isLoggedIn()) {
    header(&apos;Location: /login&apos;);
    // exit; を忘れている
}
processDelete($_GET[&apos;id&apos;]);  // → 未ログインでも削除が走る!

// ✅ 正しい: exit で確実に止める
if (!isLoggedIn()) {
    header(&apos;Location: /login&apos;);
    exit;
}
processDelete($_GET[&apos;id&apos;]);</code></pre>
<h2>HTTP ステータスの使い分け</h2>

<table border="1" cellpadding="6" cellspacing="0" style="border-collapse:collapse;width:100%">
<thead><tr style="background:#e3f2fd"><th>コード</th><th>意味</th><th>メソッド変換</th><th>用途</th></tr></thead>
<tbody>
<tr><td><strong>301</strong></td><td>Moved Permanently (恒久)</td><td>POST → GET に変わる</td><td>URL 変更、ドメイン引越し、HTTP → HTTPS</td></tr>
<tr><td><strong>302</strong></td><td>Found (一時)</td><td>POST → GET に変わる</td><td>古い実装の既定。302 でなく 303 推奨</td></tr>
<tr><td><strong>303</strong></td><td>See Other</td><td>POST → GET (明示的)</td><td>POST 完了 → GET 結果画面 (PRG パターン)</td></tr>
<tr><td><strong>307</strong></td><td>Temporary Redirect</td><td>メソッド維持</td><td>POST のまま別 URL で受け直したい</td></tr>
<tr><td><strong>308</strong></td><td>Permanent Redirect</td><td>メソッド維持</td><td>恒久的な URL 変更 + メソッド保持</td></tr>
</tbody>
</table>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php"><?php
// 恒久リダイレクト (SEO 観点で重要)
header(&apos;Location: https://example.com/new-path&apos;, true, 301);
exit;

// 一時リダイレクト
header(&apos;Location: /maintenance.php&apos;, true, 302);
exit;

// POST 後の Get-Redirect-After-Post (PRG パターン)
header(&apos;Location: /result.php?id=&apos; . $newId, true, 303);
exit;

// PHP 8 以降の関数
http_response_code(301);
header(&apos;Location: /new-path&apos;);
exit;</code></pre>
<h2>「Cannot modify header information」エラー</h2>

<p>PHP 最大の頻出エラーの一つ:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-text">Warning: Cannot modify header information - headers already sent by
(output started at /var/www/index.php:12) in /var/www/login.php on line 25</code></pre>
<p>原因は<strong>header() を呼ぶ前にすでに何かが出力されている</strong>こと。次のいずれか:</p>

<ol>
<li><code><?php</code> の<strong>前に空白や HTML</strong>がある</li>
<li>BOM 付き UTF-8 で保存されている (先頭 3 バイトの不可視 BOM)</li>
<li><code>echo</code> / <code>print</code> / <code>var_dump</code> をすでに実行している</li>
<li><strong>include 先のファイル末尾に空行</strong>がある</li>
<li><strong>PHP の Warning / Notice</strong> がすでに出力されている</li>
</ol>

<h3>対処</h3>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php"><?php
// 1. ファイル先頭の空白を削除
// 2. ?> を省略する (PHP 専用ファイルでは閉じタグ不要)
// 3. BOM なし UTF-8 で保存
// 4. include ファイルの末尾も同様に注意

// 緊急回避: 出力バッファリング
ob_start();
echo "ここで出力されても OK (バッファに溜まる)";
header(&apos;Location: /target&apos;);
ob_end_clean();   // バッファ破棄
exit;</code></pre>
<h2>絶対 URL vs 相対 URL</h2>

<p>HTTP 1.1 仕様上、Location ヘッダーは<strong>絶対 URL が原則</strong>ですが、HTTP 1.1 以降は相対 URL も受け入れます。可搬性を優先するなら絶対 URL:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php"><?php
// 絶対 URL を組み立てる
$scheme = (isset($_SERVER[&apos;HTTPS&apos;]) && $_SERVER[&apos;HTTPS&apos;] !== &apos;off&apos;) ? &apos;https&apos; : &apos;http&apos;;
$host = $_SERVER[&apos;HTTP_HOST&apos;];
$path = &apos;/dashboard&apos;;

header("Location: $scheme://$host$path", true, 302);
exit;

// 簡易ヘルパー
function redirect(string $path, int $code = 302): void {
    $scheme = (!empty($_SERVER[&apos;HTTPS&apos;]) && $_SERVER[&apos;HTTPS&apos;] !== &apos;off&apos;) ? &apos;https&apos; : &apos;http&apos;;
    $host = $_SERVER[&apos;HTTP_HOST&apos;] ?? &apos;localhost&apos;;
    header("Location: $scheme://$host$path", true, $code);
    exit;
}

redirect(&apos;/login&apos;, 302);</code></pre>
<h2>JavaScript リダイレクト</h2>

<p>PHP 出力後にどうしてもリダイレクトしたい場合の最終手段:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-html"><script>
  // 履歴に残らない (replace)
  location.replace(&apos;/target&apos;);

  // 履歴に残る (戻るボタンで戻れる)
  location.href = &apos;/target&apos;;
</script>

<!-- メタリフレッシュ (SEO 評価が下がるので非推奨) -->
<meta http-equiv="refresh" content="0; url=/target">

<!-- 3 秒後にリダイレクト -->
<meta http-equiv="refresh" content="3; url=/target"></code></pre>
<h2>セキュリティ: オープンリダイレクト脆弱性</h2>

<p>ユーザー入力をそのまま Location に使うのは危険:</p>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php"><?php
// ❌ 危険: 外部 URL に飛ばせるオープンリダイレクト
$next = $_GET[&apos;next&apos;] ?? &apos;/&apos;;
header("Location: $next");
exit;
// → /login?next=https://evil.com で攻撃可能

// ✅ ホワイトリスト方式
$allowed = [&apos;/dashboard&apos;, &apos;/mypage&apos;, &apos;/cart&apos;, &apos;/&apos;];
$next = $_GET[&apos;next&apos;] ?? &apos;/&apos;;
if (!in_array($next, $allowed, true)) {
    $next = &apos;/&apos;;
}
header("Location: $next");
exit;

// ✅ 同一ドメイン制約
$next = $_GET[&apos;next&apos;] ?? &apos;/&apos;;
if (preg_match(&apos;#^/(?!/)#&apos;, $next) !== 1) {  // / で始まり // で始まらない
    $next = &apos;/&apos;;
}
header("Location: $next");
exit;</code></pre>
<h2>Laravel での書き方</h2>
<pre style="background:#1e293b;color:#e2e8f0;padding:1em;border-radius:6px;overflow-x:auto;line-height:1.5"><code class="language-php">// シンプルなリダイレクト
return redirect(&apos;/home&apos;);

// 名前付きルート
return redirect()->route(&apos;dashboard&apos;);

// 直前のページに戻る (フォームエラー時)
return back()->withInput()->withErrors($errors);

// 外部 URL
return redirect()->away(&apos;https://example.com&apos;);

// HTTP ステータス指定
return redirect(&apos;/login&apos;, 302);
return redirect()->route(&apos;home&apos;, [], 301);

// アクション直接呼び出し
return redirect()->action([UserController::class, &apos;index&apos;]);

// セッションへフラッシュメッセージ付与
return redirect(&apos;/dashboard&apos;)->with(&apos;status&apos;, &apos;保存しました&apos;);</code></pre>
<h2>FAQ</h2>

<p><strong>Q: 301 と 302 はどう違う?</strong><br />
A: 301 は<strong>恒久</strong>。検索エンジンが古い URL を捨てて新 URL を採用、ブラウザもキャッシュする。一時的変更なら 302/303 を使う。SEO 引越しは必ず 301。</p>

<p><strong>Q: POST フォーム送信後のリダイレクトはどれ?</strong><br />
A: <strong>303 See Other</strong> が正解。302 だと再 POST の可能性がある (古いブラウザ)。<strong>PRG パターン</strong> (Post-Redirect-Get) で二重送信防止。</p>

<p><strong>Q: クッキーをセットしつつリダイレクトしたい</strong><br />
A: <code>setcookie()</code> も<strong>出力前に</strong>呼ぶ。<code>setcookie('key', $val); header('Location: /'); exit;</code> の順で OK。</p>