OriginalUri Extractor
Learn how to access the original request URI before Axum nest rewriting changes the path in nested routers
A request enters Axum carrying a URI, which is the path portion of the URL the client asked for. If you visit http://example.com/api/users, the URI is /api/users. But Axum can rewrite that URI before your handler sees it. The OriginalUri extractor is how you recover the URI as the client originally sent it, before any rewriting happened.
The Problem That OriginalUri Solves
To understand OriginalUri, you first need to know what Axum does with nested routers. The nest method lets you attach an entire sub-router under a path prefix. For example, you might nest all user-related routes under /api so they become /api/users, /api/posts, and so on.
Here is where the rewriting happens. When Axum nests a router under a prefix, it strips that prefix from the URI before handing the request to the inner router. A request to /api/users arrives at the outer router with the full path. The nest layer matches /api, removes it, and passes the request to the inner router with a URI of /users. The inner handler never sees the /api part.
That stripping is convenient most of the time. Your inner router can define routes like /users without caring about the outer prefix. But sometimes you genuinely need to know what the client actually asked for. Logging is the classic example: you want your access log to record /api/users, not /users. Redirects are another: if you generate a link back to the current page, you need the full original path, not the stripped version.
OriginalUri exists to preserve that information. It captures the URI before any nest rewriting takes place and makes it available to your handler.
A Mental Model:
Think of a request as a letter with an address written on the envelope. When the letter enters a large building, the front desk might write a shorter room number on a sticky note and forward it. The envelope still has the original address. OriginalUri lets you read the envelope, while the regular Uri extractor shows you only the sticky note.
First Look at the OriginalUri Syntax
OriginalUri is a tuple struct that wraps an http::Uri. The Uri type comes from the http crate and represents a request URI. When you use OriginalUri as a handler argument, you destructure it to get the inner Uri.
Here is the smallest possible example:
// src/main.rs
use axum::{
extract::OriginalUri,
routing::get,
Router,
};
async fn show_uri(OriginalUri(uri): OriginalUri) -> String {
format!("The original URI is: {}", uri)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(show_uri));
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();
}
The handler takes OriginalUri(uri) as a parameter. That pattern destructures the tuple struct and gives you the inner http::Uri bound to the variable uri. The Uri type implements Display, which means you can format it directly into a string with format!.
Run this with cargo run and visit http://127.0.0.1:3000/. The response will be:
The original URI is: /
There is no nesting in this example, so the URI has not been rewritten. OriginalUri returns exactly what the client sent. The regular Uri extractor would return the same thing here because no rewriting took place.
No Nest Means No Difference:
When your router has no nest calls, OriginalUri and the regular Uri extractor return identical values. You only need OriginalUri when nesting is involved. Seeing the same output from both in a flat router is expected, not a bug.
OriginalUri in a Nested Router
Now consider a router with nesting. The outer router nests an inner router under /api. The inner router defines a route at /users. A request to /api/users should be handled by the inner route, but the inner handler sees a rewritten URI.
Here is the full example:
// src/main.rs
use axum::{
extract::OriginalUri,
http::Uri,
routing::get,
Router,
};
async fn inner_handler(
OriginalUri(original_uri): OriginalUri,
current_uri: Uri,
) -> String {
format!(
"Original URI: {}\nCurrent URI: {}",
original_uri, current_uri
)
}
#[tokio::main]
async fn main() {
let api_routes = Router::new().route("/users", get(inner_handler));
let app = Router::new().nest("/api", api_routes);
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();
}
This handler takes both OriginalUri and Uri. Note the asymmetry in the parameter list: OriginalUri is a tuple struct, so it destructures as OriginalUri(original_uri), while Uri is a plain struct taken as an ordinary argument. The Uri extractor returns the URI as the current router sees it. In a nested router, that is the stripped version.
Start the server and request http://127.0.0.1:3000/api/users. The response body will be:
Original URI: /api/users
Current URI: /users
The two values are different. OriginalUri gives you /api/users, which is what the client actually typed. Uri gives you /users, which is what the inner router sees after the nest layer stripped the /api prefix.
The nest call on the outer router is what triggers the rewriting. The outer router matches the /api segment, removes it from the URI, and forwards the request to the inner router with the shortened path. OriginalUri works by looking at a value that Axum stores in the request extensions before that stripping happens. When your handler asks for OriginalUri, Axum retrieves that stored value. If no stripping occurred, it falls back to the current URI.
The Most Common Mistake:
Beginners often assume that Uri inside a nested router returns the full path the client requested. That is incorrect. Inside a nested router, Uri returns the rewritten path with the prefix removed. If you need the full original path, you must use OriginalUri.
Using OriginalUri for Request Logging
Logging is the most common real-world use for OriginalUri. When you log incoming requests, you want the record to reflect what the client actually asked for. A log entry showing /users when the client requested /api/users would be misleading, especially when you have multiple nested routers with different prefixes.
Here is an example that logs the original URI alongside the current one:
// src/main.rs
use axum::{
extract::OriginalUri,
http::Uri,
routing::get,
Router,
};
async fn log_and_respond(
OriginalUri(original_uri): OriginalUri,
current_uri: Uri,
) -> String {
println!("Request arrived for: {}", original_uri);
println!("Inner router sees: {}", current_uri);
format!("Logged request for: {}", original_uri)
}
#[tokio::main]
async fn main() {
let api_routes = Router::new().route("/users", get(log_and_respond));
let app = Router::new().nest("/api", api_routes);
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();
}
Request http://127.0.0.1:3000/api/users and check the terminal where the server runs. You will see:
Request arrived for: /api/users
Inner router sees: /users
The handler prints both values so you can compare them. In a production application, you would send the original_uri value to your logging system, not current_uri. The log entry should record the client-facing path so that anyone reading the logs later can reconstruct exactly which URL was requested.
Broken Redirects Without OriginalUri:
If you generate a redirect or a self-referencing link inside a nested router and build it from the Uri extractor, you will produce a URL that is missing the nest prefix. A user requesting /api/users might be redirected to /users, which either does not exist or points to a completely different part of your application. Use OriginalUri whenever you build URLs that the client should be able to follow back.
Working With the Inner http::Uri
The value inside OriginalUri is an http::Uri, which is the same type Axum uses for request URIs everywhere. That type has several useful methods. You can call .path() to get just the path portion without any query string, .query() to get the query string if one exists, and .host() to get the host if the URI is absolute.
Here is an example that breaks the original URI into its parts:
// src/main.rs
use axum::{
extract::OriginalUri,
routing::get,
Router,
};
async fn inspect_uri(OriginalUri(uri): OriginalUri) -> String {
let path = uri.path();
let query = uri.query().unwrap_or("no query string");
let host = uri
.host()
.map(|h| h.to_string())
.unwrap_or_else(|| "no host".to_string());
format!("Path: {}\nQuery: {}\nHost: {}", path, query, host)
}
#[tokio::main]
async fn main() {
let inner_routes = Router::new().route("/search", get(inspect_uri));
let app = Router::new().nest("/v1", inner_routes);
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();
}
Request http://127.0.0.1:3000/v1/search?q=axum&page=2. The response will be:
Path: /v1/search
Query: q=axum&page=2
Host: no host
The .path() method returns the full original path including the nest prefix. The .query() method returns the query string exactly as sent. The .host() method returns None here because the client sent a relative URI, not an absolute one. That is normal for HTTP requests - browsers typically send only the path and query, not the host.
This example shows that OriginalUri gives you access to every part of the original request URI. You can use those methods to build custom responses, extract specific query parameters, or construct absolute URLs by combining the host from a header with the path from OriginalUri.
What Beginners Usually Misunderstand
The biggest misconception has already been covered: believing that Uri inside a nested router returns the original path. That is the single most common source of confusion. But there are a few more worth naming explicitly.
The first is about destructuring. OriginalUri is a tuple struct, which means you can write OriginalUri(uri) as the handler parameter to bind the inner Uri directly. (You do not have to destructure it: OriginalUri dereferences to Uri, so methods like .path() also work on the wrapper itself.)
The second is about where OriginalUri works. It is a parts-only extractor, meaning it reads from the request head and does not consume the body. You can use it alongside body extractors like Json or String. It does not need to be the last argument in your handler, because it never touches the body. This is different from body-consuming extractors, which must be last.
The third is about when OriginalUri is needed. If your router has no nesting, using OriginalUri instead of Uri gives you no benefit. Both return the same value. Only when a nest call is present does the difference appear. Using OriginalUri everywhere out of habit adds visual noise without changing behavior.
OriginalUri and MatchedPath Are Different:
MatchedPath returns the route pattern that matched, such as /users/{id}. That is not the same as OriginalUri. MatchedPath shows you the template, while OriginalUri shows you the actual path the client sent with real values filled in. For a request to /api/users/42, OriginalUri returns /api/users/42 and MatchedPath returns the full combined template /api/users/{id} (the nest prefix is included).
Summary
The key insight from this page is that OriginalUri freezes the URI at the moment the request enters the application, before any routing layer modifies it. That makes it the correct tool whenever you need to know what the client actually requested, rather than what the current routing layer sees.
If you are logging requests, generating self-referencing links, doing analytics, or building redirects, reach for OriginalUri. If you only need the path as the current router understands it, the regular Uri extractor is sufficient and often clearer about your intent. The distinction only matters inside nested routers, which is where prefix stripping happens. The habit to build is simple: whenever a value you produce will be seen by the client or stored in a log, ask whether it came from the rewritten URI or the original one, and pick the extractor that answers that question.