Nest Path Prefix in Axum Routing
Learn how the path prefix works when nesting routers with the nest method in Axum, how prefixes combine, and common patterns for organizing routes.
When you build a web application with Axum, you will often have groups of related endpoints. For example, all user-related routes might live under /users, all product routes under /products, and all admin routes under /admin. Instead of writing the full path in every single route definition, Axum gives you the nest method. This page focuses on one specific aspect of that method: how the path prefix works. That prefix is the string you pass as the first argument to nest, and it is what makes nested routers so powerful for organizing your application.
A Simple Router Without Nesting
Before we talk about prefixes, let's look at a small Axum application that does not use nest at all. This will make the improvement obvious.
use axum::{Router, routing::get};
async fn user_list() -> &'static str {
"List of users"
}
async fn user_detail() -> &'static str {
"Single user details"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", get(user_list))
.route("/users/{id}", get(user_detail));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here we have two routes that both start with /users. That is fine for a small example. But imagine you have twenty user endpoints, plus product endpoints, plus order endpoints. The repeated /users prefix becomes noisy and easy to mistype. Worse, if you later decide to move all user routes under /api/v1/users, you would have to change every single route line. The nest method solves exactly this problem.
What is a prefix?:
A prefix is a string that goes at the beginning of every path. When you nest a router under a prefix like "/users", every route inside that nested router automatically has /users added to its own path. So a route defined as "/" inside the nested router matches /users from the outside (the bare prefix - not /users/, which is a different path), and a route defined as "/{id}" becomes /users/{id}.
Nesting a Router Under a Prefix
The nest method takes two arguments: the prefix string and a Router that contains the routes you want to group under that prefix. Here is the same application rewritten with nest:
use axum::{Router, routing::get};
async fn user_list() -> &'static str {
"List of users"
}
async fn user_detail() -> &'static str {
"Single user details"
}
#[tokio::main]
async fn main() {
// Create a router that only knows about paths *relative* to the prefix.
let user_routes = Router::new()
.route("/", get(user_list))
.route("/{id}", get(user_detail));
// Nest that router under "/users".
let app = Router::new()
.nest("/users", user_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
What changed? We made a separate user_routes router. Inside it, the paths are relative. The route for listing users is just "/" (the root of the nested router). The route for a single user is "/{id}". Then we call .nest("/users", user_routes) on the main router. Axum combines the prefix and the inner paths to form the full paths:
/users+/becomes/users(the bare prefix - a route at"/"inside a nested router matches the prefix itself, not the prefix with a trailing slash)/users+/{id}becomes/users/{id}
Run this server and try both forms: http://127.0.0.1:3000/users shows List of users, while http://127.0.0.1:3000/users/ returns 404, because the nested "/" route matches only the bare prefix.
You have split your routes cleanly:
The route definitions for users no longer mention /users at all. That prefix lives in one place: the .nest("/users", ...) call. Changing the prefix to /api/v1/users later is a one-line change.
How the Prefix Combines with Inner Paths
The rule is simple: the final path is the prefix joined with the inner path, with a slash between them. Axum does not insert a slash if the prefix already ends with a slash, and it does not remove slashes from the inner path. But to keep things predictable, the common convention is:
- Prefix does not end with a slash (e.g.,
"/users") - Inner paths do start with a slash (e.g.,
"/","/{id}")
When you follow this convention, the combination is just string concatenation: prefix + inner path. Let's look at a few examples:
Prefix "/api", inner path "/health" → full path "/api/health"
let health_routes = Router::new()
.route("/health", get(health_check));
let app = Router::new()
.nest("/api", health_routes);
Now GET /api/health works.
Prefix "/api/v1", inner path "/users" → full path "/api/v1/users"
let users_api = Router::new()
.route("/users", get(list_users));
let app = Router::new()
.nest("/api/v1", users_api);
Prefix "/" (root) with inner path "/users" → panics
Nesting at the root is not supported in Axum 0.8: nest("/", ...) panics immediately with Nesting at the root is no longer supported. Use merge instead. If you want to combine routers without adding a prefix, use merge instead of nest. (Using the inner router directly as the app also works.)
Prefix "/users/" (trailing slash) with inner path "/{id}" → full path "/users/{id}"
A trailing slash on the prefix is tolerated: nesting under "/users/" with an inner route "/{id}" still matches /users/42 - Axum does not produce a double-slash path. What does not match is a double slash in the request itself (/users//42 returns 404). Prefer prefixes without a trailing slash for clarity.
Double slashes in the request do not match:
If you write .nest("/users/", router) and inside that router you define a route at "/profile", a request to /users/profile still matches - the trailing slash on the prefix does not create a double-slash route. What does not match is a request that itself contains a double slash, like /users//profile, which returns 404. Axum does not normalize slashes in request paths, so keep your prefixes clean (no trailing slash) and your clients will not hit this either way.
Nesting Multiple Routers with Different Prefixes
You can nest several routers, each with its own prefix, in the same main router:
use axum::{Router, routing::get};
async fn get_user() -> &'static str { "User" }
async fn get_product() -> &'static str { "Product" }
async fn get_order() -> &'static str { "Order" }
#[tokio::main]
async fn main() {
let user_routes = Router::new().route("/", get(get_user));
let product_routes = Router::new().route("/", get(get_product));
let order_routes = Router::new().route("/", get(get_order));
let app = Router::new()
.nest("/users", user_routes)
.nest("/products", product_routes)
.nest("/orders", order_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now you have three separate sections of your application, each isolated from the others. The route definitions inside each nested router are short and clear.
But what if you want a nested router to have multiple sub-paths? You can define many routes inside a single nested router. For example, a user router might have routes for listing, creating, updating, and deleting:
use axum::{Router, routing::{get, post, put, delete}};
async fn list_users() -> &'static str { "List users" }
async fn create_user() -> &'static str { "Create user" }
async fn update_user() -> &'static str { "Update user" }
async fn delete_user() -> &'static str { "Delete user" }
#[tokio::main]
async fn main() {
let user_routes = Router::new()
.route("/", get(list_users))
.route("/", post(create_user))
.route("/{id}", put(update_user))
.route("/{id}", delete(delete_user));
let app = Router::new()
.nest("/users", user_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice that we can have both GET /users and POST /users because they are different HTTP methods. The nest prefix applies to all of them equally.
Using Path Parameters in the Prefix
The prefix itself can contain path parameters. This is useful when you want to nest a router under a dynamic segment, such as a version number or a tenant ID.
use axum::{Router, routing::get, extract::Path};
async fn get_report(Path(tenant_id): Path<String>) -> String {
format!("Report for tenant {tenant_id}")
}
#[tokio::main]
async fn main() {
// All routes inside report_routes will be under /{tenant_id}
let report_routes = Router::new()
.route("/report", get(get_report));
let app = Router::new()
.nest("/{tenant_id}", report_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here, the prefix is "/{tenant_id}". The inner router has a route at "/report". The full pattern becomes "/{tenant_id}/report". When a request comes in to /acme/report, the tenant_id path parameter will be "acme" and your handler can extract it using Path<String>. The same tenant ID could be extracted in any handler inside the nested router, because the parameter is part of the matched path.
Path parameters in the prefix are shared by all inner routes:
When you use a path parameter in the prefix, every route inside that nested router can extract that parameter. That is the point. But be careful: if two different path parameters from the prefix and inner route have the same name, Axum does not panic, but the values collide. For example, prefix "/{id}" and inner path "/{id}" would produce "/{id}/{id}". For name-based extraction (a struct or HashMap), the inner value wins - the last one defined. For positional extraction (a tuple), both values are kept in order. Either way it is confusing, so use distinct names, like "{tenant_id}" in the prefix and "{user_id}" inside.
Nesting Nested Routers (Deeper Prefixes)
You can nest a router inside another nested router. The prefixes combine naturally. This is useful for building a hierarchical API.
Suppose user profiles live under /users/profile and their settings under /users/profile/settings. The settings router is nested under "/profile" inside the profile router, and the profile router is nested under "/users" on the main router:
use axum::{Router, routing::get};
async fn get_user_profile() -> &'static str { "User profile" }
async fn get_user_settings() -> &'static str { "User settings" }
#[tokio::main]
async fn main() {
let settings_routes = Router::new()
.route("/settings", get(get_user_settings));
let profile_routes = Router::new()
.route("/profile", get(get_user_profile))
.nest("/profile", settings_routes);
let app = Router::new()
.nest("/users", profile_routes);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now the paths are:
/users/profile→get_user_profile/users/profile/settings→get_user_settings
This shows how prefixes combine: the outer prefix /users plus the inner nested prefix /profile plus the route /settings gives /users/profile/settings. Each level only knows its own prefix, and the full path is the concatenation of all of them in order.
Note what happens if you merge instead of nesting at the middle level: merging settings_routes into profile_routes puts /settings at the same level as /profile, giving /users/settings rather than /users/profile/settings. Nest when the group belongs under a shared segment; merge when it belongs beside the other routes.
Nesting depth is unlimited:
You can nest routers as deep as you need. Each level adds its own prefix segment. The full path is the concatenation of all prefixes in order, plus the final route path. This keeps your code organized and mirrors the URL structure exactly.
Prefix and Fallback Routes
A fallback route inside a nested router applies only to paths under that prefix. This is very useful for returning a custom 404 for a specific section of your site.
use axum::{Router, routing::get, http::StatusCode};
async fn fallback_for_users() -> (StatusCode, &'static str) {
(StatusCode::NOT_FOUND, "No such user route under /users")
}
#[tokio::main]
async fn main() {
let user_routes = Router::new()
.route("/", get(|| async { "User list" }))
.fallback(fallback_for_users);
let app = Router::new()
.nest("/users", user_routes)
.route("/", get(|| async { "Home" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
If a request comes to /users/unknown, it will hit the fallback inside the user_routes router, returning "No such user route under /users". If a request comes to /other, it will fall through to the root router's default fallback (which by default returns 404 empty). The nested fallback is scoped to the prefix.
Common Mistakes and How to Fix Them
Forgetting the leading slash in the prefix
A prefix must start with a /. If you write .nest("users", ...), Axum will panic at startup with an error like "Paths must start with a /". Always use "/users".
Trailing slash on the prefix
A trailing slash on the prefix is tolerated: nesting under "/users/" still matches /users/42 for an inner route "/{id}". What is strict is the request path itself - /users/ (with trailing slash) does not match a nested "/" route, which only matches the bare prefix /users, and a double slash in the request (/users//42) never matches. If you really want both /users and /users/ to work, define the collection route at "/" inside the nested router (which matches /users) and add an explicit "/users/" route on the parent router for the trailing-slash form. Axum does not normalize trailing slashes for you.
Trailing slash behavior can surprise beginners:
In Axum 0.8, a route at "/" inside a nested router with prefix "/users" matches /users but not /users/. They are different paths, and Axum matches paths exactly. Do not assume one route covers both forms.
Duplicate prefixes
If you nest two routers under the same prefix, their routes are merged - disjoint routes work fine. But if they define the same full path and method, registering the second one panics with an overlapping-route error (Overlapping method route. Handler for \GET /api/users` already exists). There is no "later overrides earlier". It is usually a mistake: you probably intended to nest them under different prefixes or merge them intentionally with merge`. Keep an eye on duplicate prefixes.
Overlapping prefixes
Prefixes like "/users" and "/users/admin" can coexist. Axum will match the most specific route first, because route matching is based on the full pattern. If you nest a router under /users/admin and also define a route at /users/{id}, the static segment admin will take precedence over the parameter {id}. That is standard Axum route precedence.
Real-World Pattern: API Versioning with Nest Prefix
One of the most common uses of nest prefixes is API versioning. You can create a router for each version and nest them under /api/v1, /api/v2, etc.
use axum::{Router, routing::get};
async fn v1_list_users() -> &'static str { "V1 user list" }
async fn v1_get_user() -> &'static str { "V1 user detail" }
async fn v2_list_users() -> &'static str { "V2 user list with more fields" }
async fn v2_get_user() -> &'static str { "V2 user detail" }
#[tokio::main]
async fn main() {
let v1_users = Router::new()
.route("/", get(v1_list_users))
.route("/{id}", get(v1_get_user));
let v2_users = Router::new()
.route("/", get(v2_list_users))
.route("/{id}", get(v2_get_user));
let app = Router::new()
.nest("/api/v1/users", v1_users)
.nest("/api/v2/users", v2_users);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now you have clean separation. When you release version 3, you can add another .nest("/api/v3/users", v3_users) without touching the existing code.
Prefix with Nested Services (Static Files or Other Services)
The nest_service method mounts a Tower service that is not a router (for example, a ServeDir for static files) under a prefix. The prefix works the same way: the service receives every request whose path starts with the prefix, with the prefix stripped. The same prefix rules apply - the prefix must start with /, "/" is not a valid prefix, and wildcards are not allowed in the prefix. Use nest for routers and nest_service for services.
Summary: The Prefix Is a Naming Tool That Keeps Routes Organized
The nest path prefix is a simple but powerful concept. It lets you define a group of routes once, under one common base path, without repeating that base path in every route definition. The prefix combines with inner paths by simple concatenation (with a slash). Prefixes can themselves contain path parameters, and nesting can be done multiple levels deep. This makes your route definitions more readable, easier to change, and naturally mirrors the structure of your URL space. When you find yourself writing the same starting path over and over in .route() calls, reach for nest and give that group a prefix.
The next logical step after mastering nest prefixes is to explore how to extract the nested path inside a handler using the NestedPath extractor, or how to split your route definitions into separate modules for even better organization. But for now, you have the core idea: a prefix is a shared path segment that you apply once to a whole router.