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 を返す。1 行で書ける
  • 308 は 301 と違い、メソッドとボディを変えずにリダイレクトされる。POST 系 API の移行にも使える
  • パスパラメータの引き継ぎ、www → apex の正規化、テストまでを最小コードで示す
  • 308 はブラウザに強くキャッシュされるため、本番投入前に 307 で確認する

動作確認の想定環境は axum 0.8 系、Rust stable です。0.7 系ではパス記法が :slug になります。

背景

サイトのリニューアルやドメイン統合では、旧 URL から新 URL への恒久的なリダイレクトが必要になります。かつては 301 が定番でした。しかし 301 は、古いクライアントが POST を GET に書き換えることがあります。

そこで RFC 7538 の 308 を使います。

ステータス 意味 メソッド変更 キャッシュ
301 恒久移動 GET に変わりうる 強い
302 一時移動 GET に変わりうる 弱い
303 See Other GET に変わる 弱い
307 一時移動 変わらない 弱い
308 恒久移動 変わらない 強い

axum の Redirect との対応は次のとおりです。

axum のメソッド ステータス
Redirect::to 303
Redirect::temporary 307
Redirect::permanent 308

to が 303 である点は意外と見落とされがちです。

検証 / 実装

準備

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

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

パターン 1: 固定パスの 308

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

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/old-path", any(|| async { Redirect::permanent("/new-path") }))
        .route("/new-path", any(|| async { "moved!" }));

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

get ではなく any を使うと、POST や PUT でも 308 が返ります。API のエンドポイント移行ではこちらが有用です。

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

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

use axum::{extract::Path, response::{IntoResponse, Redirect}, http::StatusCode, routing::get, Router};

async fn legacy_blog(Path(slug): Path<String>) -> impl IntoResponse {
    // ヘッダ値として不正な文字を弾く (Redirect は不正値だと panic するため)
    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()
}

fn legacy_routes() -> Router {
    Router::new().route("/blog/{slug}", get(legacy_blog))
}

Redirect::permanent は、渡された文字列が Location ヘッダ値として不正な場合に panic します。Path はパーセントデコード済みの値を返すため、改行コードなどが混入しえます。ユーザー入力を埋め込むときは、上のように許可文字を絞るのが安全です。

パターン 3: www → apex をミドルウェアで正規化

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

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 == "www.example.com" {
        let pq = req
            .uri()
            .path_and_query()
            .map(|p| p.as_str())
            .unwrap_or("/");
        return Redirect::permanent(&format!("https://example.com{pq}")).into_response();
    }
    next.run(req).await
}

pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "ok" }))
        .layer(middleware::from_fn(canonical_host))
}

ポイントは 2 つです。

  1. リダイレクト先ホストを固定文字列にする: Host ヘッダをそのまま Location に使うと、オープンリダイレクトの原因になります。比較は完全一致にし、遷移先は定数で持ちます。
  2. クエリ文字列を落とさない: path_and_query() を使えば ?utm_source=... などが維持されます。

パターン 4: リバースプロキシ背後での HTTP → HTTPS

TLS 終端をロードバランサやリバースプロキシに任せている場合は、X-Forwarded-Proto を見て判定します。

async fn force_https(req: Request, next: Next) -> Response {
    let proto = req
        .headers()
        .get("x-forwarded-proto")
        .and_then(|v| v.to_str().ok());

    if proto == Some("http") {
        let pq = req
            .uri()
            .path_and_query()
            .map(|p| p.as_str())
            .unwrap_or("/");
        return Redirect::permanent(&format!("https://example.com{pq}")).into_response();
    }
    next.run(req).await
}

このヘッダは信頼できるプロキシが付与する前提です。直接インターネットに公開するサーバーでは、クライアントが偽装できます。その場合はプロキシ側でのリダイレクトを推奨します。

パターン 5: tower::ServiceExt::oneshot でテスト

サーバーを起動せずにテストできます。パターン 3 の app() を対象にします。

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

    #[tokio::test]
    async fn www_is_redirected_with_query() {
        let res = app()
            .oneshot(
                Request::builder()
                    .uri("/a?x=1")
                    .header(header::HOST, "www.example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
        assert_eq!(res.headers()[header::LOCATION], "https://example.com/a?x=1");
    }

    #[tokio::test]
    async fn apex_passes_through() {
        let res = app()
            .oneshot(
                Request::builder()
                    .uri("/")
                    .header(header::HOST, "example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();

        assert_eq!(res.status(), StatusCode::OK);
    }
}

cargo test で、ステータスと Location の両方を検証できます。

結果

  • 固定リダイレクトは 実質 1 行で書ける
  • any を使えば POST を含むメソッドを保ったまま恒久移転できる
  • ミドルウェア化すると、ホスト正規化やスキーム強制をルート定義と分離できる
  • テストは oneshot でネットワーク不要になる

ハマりどころ

308 はブラウザが強くキャッシュする

誤った 308 を一度返すと、ユーザーのブラウザに残り続けることがあります。サーバー側を直しても反映されません。次の手順を推奨します。

  1. 最初は Redirect::temporary (307) で本番投入し、挙動を確認する
  2. 問題がなければ Redirect::permanent (308) に切り替える

リダイレクトチェーンを作らない

http://www.example.com → https://www.example.com → https://example.com のように複数段になると、クローラーの評価や表示速度に悪影響があります。1 ホップで最終 URL に到達させる設計にしてください。検索流入を意識するサイトでは、AI や検索エンジンから見たときの URL 正規化も含めて点検すると効果的です。

確認は curl で

curl -sI -H "Host: www.example.com" http://127.0.0.1:3000/a?x=1

-L を付けず、まず HTTP/1.1 308 と location を目視で確認します。

まとめ

  • axum では Redirect::permanent が 308、temporary が 307、to が 303
  • メソッド維持が必要な恒久移転には 308 を使う
  • Location に外部入力を使うときは、許可文字の制限と固定ホストでオープンリダイレクトと panic を防ぐ
  • 本番投入は 307 → 308 の順で、キャッシュ事故を避ける

参考リンク


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

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