expression
Axum: nest a router under a prefix
Nesting groups related routes under a common prefix. A child route /items becomes /api/items. Do not assume a nested router automatically authenticates requests or applies security policy. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): 200 404 Common mistake: Registering the prefix in both the child and the parent.
Formal Syntax & Structure
rust syntaxrust
Router::new().nest("/api", child)Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::routing::get; let api = Router::new().route("/items", get(|| async { "items" })); let app = Router::new().nest("/api", api); for uri in ["/api/items", "/items"] { let r = app.clone().oneshot(Request::builder().uri(uri).body(Body::empty()).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); }}