Static Route Paths in Axum
Learn how to define fixed URL paths in Axum, understand exact matching behavior, handle duplicate routes and trailing slashes, and build a simple server with multiple static endpoints.
In Axum, a static route path is a URL pattern that contains only fixed text and no dynamic parts like {id}. Examples are "/", "/users", "/about", or "/api/health". A request arrives with a URL, Axum looks at the path part of that URL (everything after the domain, before any ? query), and compares it against each static path you registered. If the whole string matches exactly, the corresponding handler runs.
This page focuses exclusively on static paths. It does not cover route parameters, wildcards, or fallbacks - those have their own lessons. Here we build a solid mental model for the simplest and most common kind of route.
Why Static Paths Exist
Most web applications have endpoints whose URLs are always the same. A health check at /health, a homepage at /, an about page at /about, a version endpoint at /api/v1/status. These paths never change from request to request. Static route paths let you map each of these fixed URLs to a specific handler function in a clear, predictable way.
Think of static paths like the table of contents in a book. Every chapter is always at the same page number. You don't have to guess what the URL will look like - you type /health and the server runs the health check handler. No surprise, no variable substitution. That predictability makes debugging easier and lets tools like load balancers and monitoring services know exactly where to look.
Your First Static Route
Before we go further, here is a complete, runnable main.rs to start from. Create a new Rust binary project, add axum and tokio to Cargo.toml, and put this code in src/main.rs:
use axum::{
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Welcome to the homepage!" }))
.route("/health", get(|| async { "OK" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
This registers two static routes: / and /health. The get(...) part means only HTTP GET requests are accepted. The handler is a closure that returns a string. When you run the server and open http://127.0.0.1:3000/ in a browser, you see the welcome message. Opening http://127.0.0.1:3000/health shows OK.
Notice how each .route() call adds one static path. The first argument is a string literal, and Axum stores it exactly as written. There is no special syntax, no pattern matching - just a plain string.
How Exact Matching Works
When Axum receives a request, it takes the request's URI path - for example, /health - and looks through all the routes you registered. It compares the incoming path to each registered static path byte for byte. If they are identical, that route matches.
This means all of the following are considered different paths:
/Health(uppercase H)/health/(trailing slash)/health?x=1(the?starts the query string, which is not part of the path for matching, but the path portion is still/health)
Only the path component is used for matching. Query strings (?key=value) are ignored. Fragment identifiers (#section) never even reach the server. So /health?foo=bar still matches the /health route.
Here is an example with several static routes that are intentionally similar but distinct:
let app = Router::new()
.route("/", get(|| async { "root" }))
.route("/about", get(|| async { "about page" }))
.route("/about/team", get(|| async { "team page" }))
.route("/about/", get(|| async { "about page with trailing slash" }));
If you visit /about/team, you get "team page". If you visit /about/, you get the trailing slash version. If you visit /about/team/, Axum will not find a matching route and will respond with 404 Not Found because there is no route for that exact path. Keep this in mind: static paths do not automatically ignore trailing slashes.
Building a Small API with Static Paths
Static paths are perfect for simple read-only endpoints. Imagine you are building a service that tells you the current server time, a list of available features, and a static version string. All three URLs are fixed, so you can register them as static routes. The first example uses JSON, so add serde_json to Cargo.toml alongside axum and tokio:
[dependencies]
axum = "0.8"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
use axum::{
routing::get,
Router,
Json,
};
use serde_json::json;
async fn time() -> Json<serde_json::Value> {
Json(json!({ "time": "2026-08-31T12:00:00Z" }))
}
async fn features() -> &'static str {
"Features: users, posts, comments"
}
async fn version() -> &'static str {
"v1.2.3"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/api/time", get(time))
.route("/api/features", get(features))
.route("/api/version", get(version));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now GET /api/time returns a JSON response, GET /api/features returns a plain string, and GET /api/version returns the version. Each path is a literal string with no variables. The prefix /api is just part of the static path; there is nothing special about it unless you later decide to group routes with nest (a different topic).
Everything Works When Paths Match Exactly:
If you start the server and use a tool like curl http://127.0.0.1:3000/api/time, you should see the JSON output. That confirms your static route registered correctly and Axum matched the path exactly. Any other path, like /api/time/ or /API/time, returns 404.
Registering Multiple Methods on the Same Static Path
A single static path can respond to multiple HTTP methods by chaining method routers. Here is how a static path can handle both GET and POST:
use axum::{
routing::{get, post},
Router,
};
async fn show_form() -> &'static str {
"Submit your name"
}
async fn submit_form() -> &'static str {
"Form submitted"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route(
"/contact",
get(show_form).post(submit_form),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The path /contact is still a static route. The difference is that the route now has two handlers: one for GET requests and one for POST requests. When a GET request arrives at /contact, Axum runs show_form. When a POST arrives at the same path, it runs submit_form. This works because method matching happens after path matching. The static path is the same, but the method narrows down which handler to use.
Duplicate Static Routes and Panic
A common mistake is registering two routes with the same static path and overlapping method sets. For example:
let app = Router::new()
.route("/health", get(|| async { "OK" }))
.route("/health", get(|| async { "Still OK" }));
When Axum builds the router, it will detect that two GET handlers are assigned to the exact same path and panic. The panic message is exact: Overlapping method route. Handler for 'GET /health' already exists. This is a runtime panic, not a compile-time error, because the conflict depends on the actual method filters used.
Two different methods on the same path are fine, and get combined with any is a special case worth knowing. any accepts every method, but Axum merges it with the more specific get handler instead of panicking. The specific method wins for its own requests, and any handles the rest:
let app = Router::new()
.route("/health", get(|| async { "OK" }))
.route("/health", axum::routing::any(|| async { "fallback" }));
A GET request to /health returns "OK" from the get handler. A POST request returns "fallback" from the any handler. So the rule is: the same method twice panics, but a specific method plus any merges cleanly.
Duplicate Static Paths Cause a Panic:
Do not register the same static path with overlapping HTTP methods. Axum panics when building the router, which usually crashes your server at startup. The error message will identify the conflicting path, so you can fix it before the server ever starts listening.
The solution is to merge the handlers into one method chain or choose different paths. If you genuinely need multiple handlers for the same path but different methods, chain them together in a single .route() call.
Trailing Slashes Are Significant
In Axum, /users and /users/ are two different static routes. There is no automatic redirect from one to the other. This surprises many beginners coming from frameworks that normalize trailing slashes. If you register only /users and a client requests /users/, Axum returns 404 Not Found.
To handle both, you must register both routes explicitly:
let app = Router::new()
.route("/users", get(|| async { "user list" }))
.route("/users/", get(|| async { "user list with slash" }));
If you want the same handler to run for both, you can reuse the handler function:
async fn user_list() -> &'static str {
"List of users"
}
let app = Router::new()
.route("/users", get(user_list))
.route("/users/", get(user_list));
Now both /users and /users/ return the same response. There is no built-in way to make Axum treat trailing slashes as optional for a single route; you must register both variants manually. This is a deliberate design choice to keep routing predictable and fast.
Trailing Slash Mismatch Leads to 404:
If you forget to register the trailing slash variant and a client requests /users/, they will receive 404. This often shows up when a frontend framework adds a slash to navigation links while the backend only defined the route without one. Always test both variants when deploying to production.
Static Paths vs Dynamic Paths (A One-Line Distinction)
Static paths contain no variable segments. Dynamic paths, like /users/{id}, contain placeholders that match many different URLs. This page only covers static paths. If you find yourself writing paths with {} inside them, you are moving into a different topic that deserves its own lesson. (A : in a path segment is not a dynamic placeholder in Axum 0.8 - registering a path like /users/:id panics.)
Using Static Paths for Health Checks and Monitoring
One of the most common real-world uses of static paths is a health check endpoint. Load balancers, container orchestrators, and uptime monitors periodically send a GET request to a fixed URL like /health or /ready. Because the path never changes, you can hardcode it in the monitoring configuration and trust that Axum will route it correctly.
Here is a production-style health check that returns JSON and a proper status code:
use axum::{
http::StatusCode,
routing::get,
Router,
Json,
};
use serde_json::json;
async fn health_check() -> (StatusCode, Json<serde_json::Value>) {
let healthy = true;
if healthy {
(
StatusCode::OK,
Json(json!({ "status": "ok", "version": "1.0.0" })),
)
} else {
(
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({ "status": "degraded" })),
)
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/health", get(health_check));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The route /health is static. A monitoring tool like Kubernetes or AWS Load Balancer will request exactly that path. Because Axum matches it exactly, you can rely on the endpoint being reachable as long as the server is up. If you later decide to add more health checks, you could create /health/live and /health/ready as additional static paths - all without any dynamic routing.
Multiple Static Routes in a Larger Application
As your application grows, you might have dozens of static paths. You can still register them all on the same Router. Here is the router chain with the small handler functions it uses, so the snippet is complete:
async fn home() -> &'static str { "home" }
async fn about() -> &'static str { "about" }
async fn contact() -> &'static str { "contact" }
async fn submit_contact() -> &'static str { "submitted" }
async fn login_form() -> &'static str { "login" }
async fn do_login() -> &'static str { "logged in" }
async fn logout() -> &'static str { "logged out" }
async fn status() -> &'static str { "ok" }
async fn config() -> &'static str { "config" }
async fn favicon() -> &'static str { "icon" }
let app = Router::new()
.route("/", get(home))
.route("/about", get(about))
.route("/contact", get(contact).post(submit_contact))
.route("/login", get(login_form).post(do_login))
.route("/logout", post(logout))
.route("/api/status", get(status))
.route("/api/config", get(config))
.route("/favicon.ico", get(favicon));
Each path is a fixed string. Axum will match the incoming request's path against all of these static routes. Since no two paths are identical, there is no conflict. The order in which you call .route() does not affect matching for static paths, because each path is unique. Axum stores them in a data structure that allows fast lookup regardless of registration order.
Static Paths Are Case-Sensitive:
URL paths are case-sensitive in Axum by default. /About and /about are different routes. If your application needs case-insensitive matching, you would have to implement that yourself (for example, by normalizing the incoming path in middleware - a different topic). Always use lowercase paths for consistency unless you have a specific reason not to.
A Complete Example with Multiple Static Routes
Let's bring everything together in one complete, runnable program. This example defines four static paths, each with a different purpose, and shows how they coexist peacefully.
use axum::{
routing::{get, post},
Router,
response::Html,
};
async fn home() -> Html<&'static str> {
Html("<h1>Welcome</h1><p>This is the homepage.</p>")
}
async fn about() -> &'static str {
"About us page"
}
async fn contact_page() -> Html<&'static str> {
Html("<h2>Contact</h2><form method='post'><button type='submit'>Send</button></form>")
}
async fn submit_contact() -> &'static str {
"Thank you for contacting us"
}
async fn health() -> &'static str {
"healthy"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about))
.route("/contact", get(contact_page).post(submit_contact))
.route("/health", get(health));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
To test this, run cargo run and visit the following URLs:
http://127.0.0.1:3000/shows the homepage HTML.http://127.0.0.1:3000/aboutshows "About us page".http://127.0.0.1:3000/contactshows a form (GET).- Submitting that form (POST to
/contact) shows "Thank you for contacting us". http://127.0.0.1:3000/healthshows "healthy".
All four routes are static. There are no parameters, no wildcards, no fallbacks. Each one matches one and only one URL path exactly. That is the essence of static route paths.
What Happens When No Static Route Matches
If a request arrives with a path that does not match any registered static route, Axum responds with 404 Not Found and an empty body. You can customize this by adding a fallback route, but that is a separate topic. For now, know that undefined paths simply fall through and produce a 404 with nothing in the body.
Checking Your Understanding
Before moving on, make sure you can answer these questions:
- How does Axum compare an incoming path to a static route?
- Why does registering
/usersand/users/require two separate routes? - What happens if you register two GET routes for
/healthon the same router? - Can a static path contain a brace, like
{id}? If you think it can, reconsider - what would that make it? (And what happens if you put a:in a path segment?)
If you are unsure about any of these, reread the relevant section. Static paths are the foundation of routing in Axum. Once you understand them completely, you are ready to explore paths with variable segments - but that subject belongs elsewhere.
Summary
Static route paths are the simplest form of routing in Axum. They are literal strings that match the request's URL path exactly. You register them with .route(), specify one or more method handlers, and Axum takes care of dispatching requests. Key takeaways: duplicate paths with overlapping methods panic, trailing slashes are significant, and case sensitivity applies. Static paths are ideal for fixed endpoints like health checks, version endpoints, and top-level pages where the URL never changes. With this understanding, you can confidently build a server whose routes are predictable and easy to debug.
Once you internalize exact matching, the next natural step in path patterns is to allow parts of the URL to vary - but that introduces a new set of rules and syntax that deserves its own focused lesson.