TL;DR
-
axum::response::Redirect::permanentは 308 Permanent Redirect を返す。301 と違い メソッドとボディが保持される - www 統一・HTTPS 化・末尾スラッシュ除去は、別々に書くと リダイレクトチェーン になる。1 本のミドルウェアにまとめて 常に 1 ホップ で正規 URL に飛ばす
-
HostヘッダをそのままLocationに使うと オープンリダイレクト の原因になる。ホストは許可リストで検証し、飛び先は定数で固定する -
tower::ServiceExt::oneshotを使えば、サーバーを起動せずにリダイレクトをテストできる
動作確認は Rust 1.80 以降、axum 0.8 系の想定です。
背景: なぜ 301 ではなく 308 なのか
恒久リダイレクトには 301 と 308 があります。違いは次のとおりです。
| ステータス | 意味 | メソッド保持 |
|---|---|---|
| 301 Moved Permanently | 恒久移動 | 保証なし (POST が GET に変わるクライアントがある) |
| 308 Permanent Redirect | 恒久移動 | 保持される (RFC 9110) |
API エンドポイントや Webhook の受け口は、POST が GET に化けると壊れます。新規実装なら 308 を選べば安全です。Google も 301 と 308 を同じ恒久リダイレクトとして扱うと公式ドキュメントに記載しています (参考リンク参照)。
axum の Redirect は次の 3 種類です。
| 関数 | ステータス |
|---|---|
Redirect::to |
303 See Other |
Redirect::temporary |
307 Temporary Redirect |
Redirect::permanent |
308 Permanent Redirect |
最小実装: 1 ルートだけ 308 にする
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
use axum::{response::Redirect, routing::get, Router};
async fn old_about() -> Redirect {
Redirect::permanent("/about")
}
async fn about() -> &'static str {
"about"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/about", get(about))
.route("/company", get(old_about)); // 旧URL → 新URL
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
旧 URL が数本程度ならこれで十分です。問題は サイト全体の URL 正規化 です。
本題: 3 つの正規化を 1 本のミドルウェアにまとめる
次の 3 つを個別のミドルウェアで実装すると、http://example.com/blog/ へのアクセスが 3 回リダイレクトされることがあります。
-
http→https -
example.com→www.example.com -
/blog/→/blog
クローラの巡回効率やユーザーの体感速度を考えると、必ず 1 ホップで最終形に飛ばす のが理想です。判定をまとめて、最後に 1 回だけ Redirect::permanent を返します。
use axum::{
extract::Request,
http::header,
middleware::{self, Next},
response::{IntoResponse, Redirect, Response},
routing::get,
Router,
};
const BARE_HOST: &str = "example.com";
const CANONICAL_HOST: &str = "www.example.com";
async fn canonicalize(req: Request, next: Next) -> Response {
let headers = req.headers();
// Host からポート番号を除去
let host = headers
.get(header::HOST)
.and_then(|v| v.to_str().ok())
.and_then(|h| h.split(':').next())
.unwrap_or("");
// 許可リスト外のホスト (localhost 等) は素通し
if host != BARE_HOST && host != CANONICAL_HOST {
return next.run(req).await;
}
// リバースプロキシ配下を想定 (後述の注意点を参照)
let is_http = headers
.get("x-forwarded-proto")
.and_then(|v| v.to_str().ok())
== Some("http");
let uri = req.uri();
let path = uri.path();
let need_host = host == BARE_HOST;
let need_https = is_http;
let need_slash = path.len() > 1 && path.ends_with('/');
if !(need_host || need_https || need_slash) {
return next.run(req).await;
}
// 先頭・末尾の "/" を畳む: "//evil.com/" → "/evil.com"
let path = if need_slash {
format!("/{}", path.trim_matches('/'))
} else {
path.to_string()
};
let target = match uri.query() {
Some(q) => format!("https://{CANONICAL_HOST}{path}?{q}"),
None => format!("https://{CANONICAL_HOST}{path}"),
};
Redirect::permanent(&target).into_response()
}
fn app() -> Router {
Router::new()
.route("/", get(|| async { "top" }))
.route("/blog", get(|| async { "blog" }))
.layer(middleware::from_fn(canonicalize))
}
#[tokio::main]
async fn main() {
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app()).await.unwrap();
}
ポイント解説
1. 飛び先は CANONICAL_HOST 定数で固定する
Host ヘッダは攻撃者が自由に書き換えられます。これをそのまま Location に埋め込むと、任意ドメインへ飛ばせるオープンリダイレクトになります。ここでは許可リストにあるホストだけを処理し、Location のホスト部は常に定数にしています。
2. パスの正規化でプロトコル相対 URL を防ぐ
//evil.com/ のように先頭がスラッシュ 2 つのパスをそのままトリムすると、Location: //evil.com というプロトコル相対 URL になってしまいます。trim_matches('/') で先頭・末尾を一度すべて落とし、/ を 1 つだけ付け直すことで防いでいます。
3. クエリ文字列を必ず引き継ぐ
?page=2 などを落とすと、検索結果ページや UTM 付きリンクが壊れます。uri.query() で明示的に連結します。
4. Router::layer は 404 になる前にも効く
/blog/ のような未登録パスは、通常ならフォールバック (404) に落ちます。axum の layer はフォールバックにも適用されるため、404 になる前にリダイレクトできます。逆に、認可ミドルウェアなど「マッチしたルートだけ」に効かせたい場合は route_layer を使います。
テスト: サーバー起動なしで 3 本
tower::ServiceExt::oneshot で Router に直接リクエストを流せます。
#[cfg(test)]
mod tests {
use super::*;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use tower::ServiceExt;
async fn get_with(uri: &str, host: &str, proto: &str) -> Response {
app()
.oneshot(
Request::builder()
.uri(uri)
.header("host", host)
.header("x-forwarded-proto", proto)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn bare_host_and_trailing_slash_in_one_hop() {
let res = get_with("/blog/?page=2", "example.com", "http").await;
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(
res.headers()["location"],
"https://www.example.com/blog?page=2"
);
}
#[tokio::test]
async fn canonical_url_passes_through() {
let res = get_with("/blog", "www.example.com", "https").await;
assert_eq!(res.status(), StatusCode::OK);
}
#[tokio::test]
async fn protocol_relative_path_is_neutralized() {
let res = get_with("//evil.com/", "www.example.com", "https").await;
assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT);
assert_eq!(res.headers()["location"], "https://www.example.com/evil.com");
}
}
1 本目が「3 つの正規化が 1 ホップで完了する」ことの証明です。3 本目はセキュリティ回帰テストとして残しておくと、将来の改修で壊れても気づけます。
curl での実機確認
$ cargo run &
$ curl -sI -H 'Host: example.com' -H 'X-Forwarded-Proto: http' \
'http