0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Rust + axum で 308 Permanent Redirect を最短 10 行で実装する【5 パターン + テスト付き】

0
Posted at

TL;DR

  • axum の Redirect::permanent() が返すのは 308 で、301 ではない
  • 308 は メソッドとボディを変えずに 恒久移転を伝えられる (POST が GET に化けない)
  • この記事では次の 5 パターンを、コピペで動くコードとテスト付きで紹介する
    1. 固定パスの移転
    2. パスパラメータを引き継ぐ移転
    3. クエリ文字列を引き継ぐ移転
    4. www. から apex ドメインへの統一 (middleware)
    5. oneshot によるテスト

動作確認は axum 0.7 系 / Rust stable で行っています。

背景: 301 と 308 の違い

サイトリニューアルや URL 設計の見直しでは、恒久リダイレクトが必須になります。SEO 上も、評価を新 URL へ引き継ぐために恒久リダイレクトを正しく返すことが重要です。

ステータス 意味 メソッド変更
301 Moved Permanently 恒久移転 歴史的経緯で POST → GET に変わりうる
302 Found 一時移転 同上
303 See Other 別 URL を GET せよ 常に GET へ
307 Temporary Redirect 一時移転 変えない
308 Permanent Redirect 恒久移転 変えない

axum の Redirect は次のように対応しています。

axum の関数 ステータス
Redirect::to 303
Redirect::temporary 307
Redirect::permanent 308

Redirect::to が 303 である点は、移行時に意外とハマります。

準備

# Cargo.toml
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }

[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

パターン 1: 固定パスの移転 (最短 10 行)

use axum::{response::Redirect, routing::get, Router};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old", get(|| async { Redirect::permanent("/new") }))
        .route("/new", get(|| async { "new page" }));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

curl で確認します。

curl -i http://127.0.0.1:3000/old
# HTTP/1.1 308 Permanent Redirect
# location: /new

パターン 2: パスパラメータを引き継ぐ

/blog/:slug を /articles/:slug に移す例です。

use axum::{extract::Path, response::{IntoResponse, Redirect, Response}, http::StatusCode};

async fn legacy_post(Path(slug): Path<String>) -> Response {
    // slug を許可文字だけに絞る (ヘッダ値の不正文字・意図しない URL 生成を防ぐ)
    let ok = !slug.is_empty()
        && slug.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
    if !ok {
        return StatusCode::NOT_FOUND.into_response();
    }
    Redirect::permanent(&format!("/articles/{slug}")).into_response()
}
.route("/blog/:slug", get(legacy_post))

注意点が 2 つあります。

  • Path<String> はパーセントデコード済みの値を返します。そのまま format! で URL に埋め込むと、改行や制御文字が混ざる可能性があります。Redirect::permanent は内部で HeaderValue への変換に失敗すると panic します。上のように許可文字で絞るか、パーセントエンコードし直してください。
  • axum 0.8 以降はパス記法が /{slug} に変わっています。0.8 へ上げる場合は :slug を {slug} に書き換えてください。

パターン 3: クエリ文字列を引き継ぐ

/search?q=rust を /find?q=rust へ移す例です。

use axum::{http::Uri, response::Redirect};

async fn legacy_search(uri: Uri) -> Redirect {
    let target = match uri.query() {
        Some(q) => format!("/find?{q}"),
        None => "/find".to_string(),
    };
    Redirect::permanent(&target)
}
.route("/search", get(legacy_search))

Uri は構築時に検証済みなので、query() の値をそのまま連結しても不正なヘッダ値にはなりません。

パターン 4: www から apex ドメインへ統一する (middleware)

www.example.com と example.com が両方生きていると、検索エンジンから重複コンテンツとみなされます。

use axum::{
    extract::Request,
    http::header,
    middleware::{self, Next},
    response::{IntoResponse, Redirect, Response},
    routing::get,
    Router,
};

const CANONICAL_HOST: &str = "example.com";

async fn redirect_www(req: Request, next: Next) -> Response {
    let host = req
        .headers()
        .get(header::HOST)
        .and_then(|v| v.to_str().ok())
        .unwrap_or("");

    // Host ヘッダをそのまま信用せず、固定のドメインとだけ比較する
    if host == format!("www.{CANONICAL_HOST}") {
        let pq = req
            .uri()
            .path_and_query()
            .map(|p| p.as_str())
            .unwrap_or("/");
        return Redirect::permanent(&format!("https://{CANONICAL_HOST}{pq}")).into_response();
    }
    next.run(req).await
}

fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "top" }))
        .route("/old", get(|| async { Redirect::permanent("/new") }))
        .route("/new", get(|| async { "new page" }))
        .layer(middleware::from_fn(redirect_www))
}

ポイントは、Host ヘッダから取り出した値をそのままリダイレクト先に使わないことです。それをやるとオープンリダイレクトやキャッシュポイズニングの入口になります。比較対象と遷移先は定数で固定します。

なお、実運用ではリバースプロキシ (Traefik / nginx / Cloudflare など) が Host を書き換える場合があります。その場合は X-Forwarded-Host の扱いをインフラ側と揃えてください。

パターン 5: oneshot でテストする

tower::ServiceExt::oneshot を使えば、サーバーを起動せずにルーターを直接テストできます。

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{
        body::Body,
        http::{header, Request, StatusCode},
    };
    use tower::ServiceExt;

    async fn get_res(host: &str, uri: &str) -> axum::response::Response {
        app()
            .oneshot(
                Request::builder()
                    .uri(uri)
                    .header(header::HOST, host)
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap()
    }

    #[tokio::test]
    async fn old_redirects_with_308() {
        let res = get_res("example.com", "/old").await;
        assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
        assert_eq!(res.headers()[header::LOCATION], "/new");
    }

    #[tokio::test]
    async fn www_redirects_to_apex_and_keeps_path_query() {
        let res = get_res("www.example.com", "/new?a=1").await;
        assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
        assert_eq!(res.headers()[header::LOCATION], "https://example.com/new?a=1");
    }

    #[tokio::test]
    async fn apex_is_not_redirected() {
        let res = get_res("example.com", "/new").await;
        assert_eq!(res.status(), StatusCode::OK);
    }
}
cargo test

ハマりどころ

  1. 308 はブラウザに強くキャッシュされる
    間違った移転先を返すと、利用者側のキャッシュが残って戻せなくなります。確証が持てないうちは Redirect::temporary (307) で運用し、確定してから 308 に切り替えるのが安全です。
  2. リダイレクトチェーンを作らない
    http → https → www なし → 新パス のように何段も挟むと、クロール効率も体感速度も落ちます。最終 URL へ 1 回で飛ばす設計にしましょう。
  3. 末尾スラッシュの揺れ
    /new と /new/ の扱いは別問題です。tower-http の NormalizePath を使うと統一できます。
  4. POST を 301 で返さない
    フォーム送信や API の移転で 301 を使うと、クライアントによっては GET に変わります。メソッドを保ちたいなら 308 を選びます。

まとめ

  • axum では Redirect::permanent が 308 を返す。Redirect::to は 303 なので注意
  • パスやクエリを引き継ぐときは、入力値の検証と固定プレフィックスを徹底する
  • Host ヘッダは信用せず、定数と比較する
  • oneshot でテストを書けば、リダイレクト設定の事故を CI で防げる

URL 移行の品質は検索流入に直結します。移行後の AI 検索や生成 AI 経由の露出まで見たい場合は、lookupai のような AI SEO 最適化ツールで確認するのも一案です。

参考リンク


✍️ 本記事の著者: 合同会社ジモラボ

ジモラボは、八王子を拠点に AI を活用した SaaS を多数開発しています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?