TL;DR
- axum 0.7 では
Redirect::permanent()が 308 Permanent Redirect を返す。 - 301 と違い、308 は HTTP メソッドとボディを維持したまま 転送される。API の移設でも安全に使える。
- 本記事では次の 5 パターンを、コピペで動く最小コードで紹介する。
- 固定パスの転送
- パスパラメータを引き継ぐ転送
-
www→ apex ドメインの正規化 (クエリ維持) - 旧 URL テーブルによる一括転送
-
tower::ServiceExt::oneshotによるテスト
- 最後に、ハマりやすい落とし穴 (ブラウザキャッシュ・ヘッダー不正値による panic・オープンリダイレクト) も整理する。
背景: なぜ 301 ではなく 308 か
恒久的な URL 移転といえば 301 が定番ですが、古くからの挙動として、多くのクライアントは 301 を受けると POST を GET に書き換えて 再リクエストします。
| ステータス | 恒久/一時 | メソッド維持 |
|---|---|---|
| 301 Moved Permanently | 恒久 | 保証されない (GET に変わりうる) |
| 308 Permanent Redirect | 恒久 | 維持される |
| 302 Found | 一時 | 保証されない |
| 307 Temporary Redirect | 一時 | 維持される |
| 303 See Other | - | GET に変更 |
308 は RFC 7538 で定義され、現在は RFC 9110 (§15.4.9) に統合されています。検索エンジンも 308 を 301 と同様に恒久移転として扱います。ページ移転時の評価引き継ぎ (SEO) を考えても、新規実装なら 308 を選んで困ることはほぼありません。
axum の Redirect は次の対応になっています。
| メソッド | ステータス |
|---|---|
Redirect::to |
303 See Other |
Redirect::temporary |
307 Temporary Redirect |
Redirect::permanent |
308 Permanent Redirect |
準備
# Cargo.toml
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
axum と tokio はいずれも MIT ライセンスです。ルーティングのパス構文は 0.7 系 (/:slug) で書いています。0.8 以降は /{slug} に変わるので注意してください。
パターン 1: 固定パスの転送
最もシンプルな形です。クロージャで Redirect を返すだけです。
use axum::{response::Redirect, routing::get, Router};
fn app() -> Router {
Router::new().route(
"/old-about",
get(|| async { Redirect::permanent("/about") }),
)
}
POST など他のメソッドも転送したい場合は axum::routing::any を使います。
use axum::routing::any;
let r = Router::new().route(
"/api/v1/ping",
any(|| async { Redirect::permanent("/api/v2/ping") }),
);
308 なので、クライアントが POST なら転送先にも POST が送られます。
パターン 2: パスパラメータを引き継ぐ
/posts/:slug を /blog/:slug に移したいケースです。
use axum::{
extract::Path,
http::StatusCode,
response::{IntoResponse, Redirect, Response},
};
async fn legacy_post(Path(slug): Path<String>) -> Response {
// Location ヘッダーに載せる値は必ず検証する
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!("/blog/{slug}")).into_response()
}
ルーターへの登録は次のとおりです。
.route("/posts/:slug", get(legacy_post))
Path はパーセントデコード済みの値を返します。そのまま format! で URL に埋め戻すと、制御文字などが混じる可能性があります。axum の Redirect::permanent は不正なヘッダー値だと panic するため、英数字・-・_ のホワイトリストで弾いておくと安全です。
パターン 3: www → apex の正規化 (パス・クエリ維持)
ホスト名の正規化は、ミドルウェアにすると全ルートに効きます。
use axum::{
extract::Request,
http::header,
middleware::{self, Next},
response::{IntoResponse, Redirect, Response},
};
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 let Some(apex) = host.strip_prefix("www.") {
// 検証済みの Host のみ使う
let valid = apex
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == ':');
if valid {
let pq = req
.uri()
.path_and_query()
.map(|p| p.as_str())
.unwrap_or("/");
let target = format!("https://{apex}{pq}");
return Redirect::permanent(&target).into_response();
}
}
next.run(req).await
}
アプリへの適用は layer で行います。
fn app() -> Router {
Router::new()
.route("/old-about", get(|| async { Redirect::permanent("/about") }))
.route("/posts/:slug", get(legacy_post))
.layer(middleware::from_fn(canonical_host))
}
ポイントは 2 つあります。
-
path_and_query()を使うことで、/blog/hello?x=1の クエリ文字列も欠落しません。 - リバースプロキシ配下では、スキーム判定を
X-Forwarded-Protoに頼る構成もあります。ここでは簡単のためhttps固定にしています。
パターン 4: 旧 URL テーブルによる一括転送
移行すべき URL が多いときは、fallback に静的テーブルを引かせると見通しが良くなります。
use axum::http::Uri;
static LEGACY: &[(&str, &str)] = &[
("/company", "/about"),
("/contact-us", "/contact"),
("/news/index", "/blog"),
];
async fn legacy_fallback(uri: Uri) -> Response {
let path = uri.path().trim_end_matches('/');
match LEGACY.iter().find(|(from, _)| *from == path) {
Some((_, to)) => Redirect::permanent(to).into_response(),
None => StatusCode::NOT_FOUND.into_response(),
}
}
Router::new()
// ...各ルート...
.fallback(legacy_fallback)
転送先をテーブル (コード内の固定値) だけに限定しているので、ユーザー入力が Location に混入しません。
パターン 5: oneshot でテストする
サーバーを起動しなくても、Router は tower::Service なので oneshot で直接叩けます。
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{header, Request, StatusCode},
};
use tower::ServiceExt;
async fn get_res(uri: &str, host: &str) -> axum::response::Response {
app()
.oneshot(
Request::builder()
.uri(uri)
.header(header::HOST, host)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn fixed_path_is_308() {
let res = get_res("/old-about", "example.com").await;
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(res.headers()[header::LOCATION], "/about");
}
#[tokio::test]
async fn www_keeps_path_and_query() {
let res = get_res("/blog/hello?x=1", "www.example.com").await;
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(
res.headers()[header::LOCATION],
"https://example.com/blog/hello?x=1"
);
}
#[tokio::test]
async fn invalid_slug_is_404() {
let res = get_res("/posts/a%0Ab", "example.com").await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
}
cargo test で 3 件が通れば OK です。実機では curl -I で確認できます。
curl -I -H "Host: www.example.com" "http://localhost:3000/blog/hello?x=1"
# HTTP/1.1 308 Permanent Redirect
# location: https://example.com/blog/hello?x=1
落とし穴
-
ブラウザは 308 を強くキャッシュする
一度返すと、サーバー側を直しても手元のブラウザでは転送され続けることがあります。開発中はRedirect::temporary(307) で動作確認し、本番反映時にpermanentへ切り替えるのが安全です。 -
不正なヘッダー値で panic する
Redirect::permanentは、渡した文字列がLocationとして不正だと panic します。外部入力を混ぜるなら、パターン 2 のように必ず検証してください。 -
オープンリダイレクト
?next=https://evil.exampleのような値を、そのままRedirect::permanentに渡してはいけません。転送先は固定テーブルか、自ドメイン内の相対パスに限定します。 -
リダイレクトループ
リバースプロキシ側でも HTTPS 化や www 正規化をしていると、二重に転送してループすることがあります。どの層で正規化するかを 1 か所に決めておきましょう。 -
ごく古いクライアント
308 を理解しない古い HTTP クライアントも存在します。一般的な Web 用途ではほぼ問題になりませんが、組み込み機器向け API などでは考慮が必要です。
まとめ
- 恒久転送で メソッドを保ちたいなら 308。axum では
Redirect::permanentの 1 行で書ける。 - 固定パス・パスパラメータ・ホスト正規化・テーブル転送の 4 パターンで、実務の大半はカバーできる。
-
oneshotを使えばサーバー起動なしでステータスとLocationをテストできる。 - URL 移行時に 308 や 301 を正しく設定することは、検索エンジンへの評価引き継ぎにも直結します。AI 検索や LLM 経由の流入を見据えたサイト改善では、こうしたリダイレクト設計の地味な部分が効いてきます。サイトの AI 向け最適化を手軽に試したい方は、末尾の lookupai もご覧ください。
参考リンク
- axum 公式ドキュメント (
axum::response::Redirect): https://docs.rs/axum/latest/axum/response/struct.Redirect.html - axum リポジトリ (MIT License): https://github.com/tokio-rs/axum
- tokio (MIT License): https://github.com/tokio-rs/tokio
- RFC 9110 §15.4.9 308 Permanent Redirect: https://www.rfc-editor.org/rfc/rfc9110.html#name-308-permanent-redirect
- MDN: 308 Permanent Redirect: https://developer.mozilla.org/ja/docs/Web/HTTP/Status/308
✍️ 本記事の著者: 合同会社ジモラボ
ジモラボは、八王子を拠点に AI を活用した SaaS を多数開発しています。
- 🌐 公式サイト: https://locallab.jp
- 🔍 AI SEO 最適化 SaaS: lookupai.jp
- 📺 YouTube: @locallab_llc
- ✉️ お問い合わせ: info@locallab.jp