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 を最短実装する 5 つのポイント

0
Posted at

TL;DR

  • axum の Redirect::permanent は 308 Permanent Redirect を返す (301 ではない)
  • 308 は メソッドとボディを保持したまま 恒久移転を伝えられる
  • 旧パスから新パスへの移行は、パスパラメータとクエリ文字列を引き継ぐところまで書いておく
  • www から apex ドメインへの正規化は、Host 判定をホワイトリスト化した上でミドルウェアにする
  • tower::ServiceExt::oneshot を使えば、サーバーを起動せずにステータスと Location を検証できる

動作確認環境: Rust stable / axum 0.7 / tokio 1.x

1. なぜ 301 ではなく 308 なのか

恒久リダイレクトには 301 と 308 があります。違いは リクエストメソッドの扱い です。

ステータス 意味 メソッド変更
301 Moved Permanently 恒久移転 歴史的経緯で POST → GET に変わるクライアントがある
308 Permanent Redirect 恒久移転 変更しない (保証)

API のエンドポイント移転では、POST が GET に化けると事故になります。HTML ページだけなら 301 でも問題ありませんが、新規に実装するなら 308 を選んでおけば迷いません。仕様は RFC 9110 §15.4.9 に定義されています。

axum の Redirect のステータスは次のとおりです。

関数 ステータス
Redirect::to 303 See Other
Redirect::temporary 307 Temporary Redirect
Redirect::permanent 308 Permanent Redirect

2. 最小実装 (10 行)

Cargo.toml:

[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }

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

src/main.rs:

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

3. パスパラメータとクエリを引き継ぐ

実運用では /blog/42?utm_source=x のような URL を /posts/42?utm_source=x に移すケースが多いです。クエリを落とすと計測が壊れるので、RawQuery で素通しします。

use axum::{
    extract::{Path, RawQuery},
    response::Redirect,
};

async fn legacy_post(Path(id): Path<u32>, RawQuery(q): RawQuery) -> Redirect {
    let target = match q {
        Some(q) => format!("/posts/{id}?{q}"),
        None => format!("/posts/{id}"),
    };
    Redirect::permanent(&target)
}

ルーティングに登録します。

fn app() -> Router {
    Router::new()
        .route("/blog/:id", get(legacy_post))
        .route("/posts/:id", get(|| async { "post" }))
}

axum 0.8 以降はパスパラメータの記法が /blog/{id} に変わります。バージョンに合わせて読み替えてください。

Path<u32> で型を絞っているため、数値以外は 400 系で弾かれます。リダイレクト先は必ず自分のパス (/ 始まり) に固定してください。ユーザー入力をそのまま Location にすると オープンリダイレクト脆弱性 になります。

4. www → apex の正規化ミドルウェア

SEO の観点では、www.example.com と example.com を 1 つに寄せたいことが多いです。from_fn で書けます。

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

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

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

    if host.eq_ignore_ascii_case(WWW_HOST) {
        let pq = req
            .uri()
            .path_and_query()
            .map(|p| p.as_str())
            .unwrap_or("/");
        let target = format!("https://{CANONICAL_HOST}{pq}");
        return Redirect::permanent(&target).into_response();
    }

    next.run(req).await
}

適用は 1 行です。

let app = app().layer(middleware::from_fn(canonical_host));

ポイントは次の 2 点です。

  • Host をそのまま使わず、定数と比較する。 Host ヘッダーは攻撃者が任意に書き換えられるので、任意ホストへのリダイレクトを避けるためにホワイトリスト方式にします
  • スキームは https に固定しています。リバースプロキシ配下で HTTP と HTTPS を区別したい場合は、X-Forwarded-Proto を信頼できる経路からのみ読むようにします

5. サーバーを起動せずにテストする

Router は tower の Service なので、oneshot で直接リクエストを流せます。

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

    #[tokio::test]
    async fn legacy_post_keeps_query() {
        let res = app()
            .oneshot(
                Request::builder()
                    .uri("/blog/42?utm_source=x")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
        assert_eq!(
            res.headers()[header::LOCATION],
            "/posts/42?utm_source=x"
        );
    }
}

cargo test だけで、ステータスコードと Location の回帰テストが回せます。

落とし穴: 恒久リダイレクトはブラウザにキャッシュされる

308 は仕様上キャッシュ可能で、ブラウザは強くキャッシュします。リダイレクト先を間違えたまま本番に出すと、利用者のブラウザ側に残り、サーバーを直しても戻りません。

  • 最初は Redirect::temporary (307) で動作を確認し、問題なければ permanent に切り替える
  • 検証時は DevTools の「キャッシュを無効化」を有効にするか、シークレットウィンドウを使う
  • リダイレクトの連鎖 (A→B→C) を作らず、必ず最終 URL へ 1 回で飛ばす

まとめ

  1. 恒久移転の新規実装は 301 より 308 を選ぶ (メソッドが保持される)
  2. axum では Redirect::permanent を呼ぶだけでよい
  3. 旧パスの移行では クエリ文字列を引き継ぐ
  4. ホスト正規化は ホワイトリスト比較 のミドルウェアで行う
  5. oneshot でテストし、本番投入前は 307 で様子を見る

リダイレクト設計は、地味ですが検索流入に直結する部分です。URL 移行に伴う順位低下を避けるうえでも、正しいステータスコードの選択は有効です。

参考リンク


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

ジモラボは、八王子を拠点に 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?