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 つです。
-
リダイレクト先ホストを固定文字列にする:
HostヘッダをそのままLocationに使うと、オープンリダイレクトの原因になります。比較は完全一致にし、遷移先は定数で持ちます。 -
クエリ文字列を落とさない:
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 を一度返すと、ユーザーのブラウザに残り続けることがあります。サーバー側を直しても反映されません。次の手順を推奨します。
- 最初は
Redirect::temporary(307) で本番投入し、挙動を確認する - 問題がなければ
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 の順で、キャッシュ事故を避ける
参考リンク
- axum (MIT License): https://github.com/tokio-rs/axum
- axum
Redirectドキュメント: https://docs.rs/axum/latest/axum/response/struct.Redirect.html - tokio (MIT License): https://github.com/tokio-rs/tokio
- tower (MIT License): https://github.com/tower-rs/tower
- RFC 7538 The Hypertext Transfer Protocol Status Code 308: https://www.rfc-editor.org/rfc/rfc7538
- RFC 9110 HTTP Semantics (Redirection 3xx): https://www.rfc-editor.org/rfc/rfc9110#name-redirection-3xx
✍️ 本記事の著者: 合同会社ジモラボ
ジモラボは、八王子を拠点に AI を活用した SaaS を多数開発しています。
- 🌐 公式サイト: https://locallab.jp
- 🔍 AI SEO 最適化 SaaS: lookupai.jp
- 📺 YouTube: @locallab_llc
- ✉️ お問い合わせ: info@locallab.jp