OriginalUri extractor in Axum

Learn what the OriginalUri extractor does, why it is needed when routing requests, and how to use it correctly with nested routers and path rewriting.

When a client sends an HTTP request to your Axum server, that request contains a URI (Uniform Resource Identifier) - the address the client asked for. Axum's routing system sometimes transforms that URI internally. For example, when you nest routers under a path prefix, Axum strips that prefix before matching handlers. The OriginalUri extractor gives you access to the URI exactly as the client sent it, before any of that internal rewriting happens.

What Problem Does OriginalUri Solve?

Imagine you build an API with versioning using Axum's nest method:

let app = Router::new()
    .nest("/api/v1", api_routes());

Inside api_routes, a handler might match /users. The MatchedPath extractor would show /api/v1/users - the full route pattern, including the nest prefix. But if you want to log the full URL the client actually requested, including the query string, or build a link back to the same endpoint, you need the original URI: /api/v1/users?active=true. OriginalUri recovers that untouched value.

This matters whenever your application needs to know what the client really asked for, not what Axum decided to match after applying routing transformations.

A First Example of OriginalUri

Start with a minimal Axum application that returns the original URI as a plain text response.

use axum::{
    extract::OriginalUri,
    routing::get,
    Router,
};
async fn show_original_uri(OriginalUri(uri): OriginalUri) -> String {
    format!("Original URI: {}", uri)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/hello", get(show_original_uri));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If you run this and visit http://127.0.0.1:3000/hello?name=world, the response body will be:

Original URI: /hello?name=world

Notice that the URI includes the path (/hello) and the query string (?name=world), but not the scheme (http://) or the host (127.0.0.1:3000). That is the default behavior: OriginalUri stores the origin-form URI, which is everything after the host and port in an HTTP request line. Most servers use this form because the host information is available separately via the Host header or the Host extractor.

OriginalUri Contains Origin-Form:

The OriginalUri extractor wraps a http::Uri that is in origin-form. It does not include the scheme or authority (host and port) unless the client explicitly sent them in the request target, which is rare for normal HTTP/1.1 requests. If you need the full absolute URL, combine OriginalUri with the Host extractor.

How OriginalUri Is Extracted

Axum calls OriginalUri during the "parts" extraction phase - before the handler runs and before any extractor that consumes the request body. Under the hood, it implements FromRequestParts, which means it only reads from the request's head (method, URI, headers). It never touches the request body.

Because it is a parts extractor, you can place OriginalUri anywhere in your handler's parameter list. You can also combine it with body-consuming extractors like Json or String, as long as the body extractor remains last.

The OriginalUri is not constructed by Axum from the current routing state. Instead, Axum stores the original request URI in a special extension attached to the request parts when the router starts processing. The extractor simply retrieves that stored value.

This design means the URI available to OriginalUri remains unchanged regardless of how many nested routers or middleware layers the request passes through. It is the URI from the moment the request entered the Axum router.

OriginalUri with Nested Routers

The most common reason to use OriginalUri is inside a nested router. When you call nest("/api", some_router), Axum strips the /api prefix before it tries to match routes inside some_router. As a result, a handler inside that nested router would normally see only the remaining path. OriginalUri bypasses that stripping.

Here is a complete example that demonstrates the difference between the original URI and the matched path inside a nested router:

use axum::{
    extract::{MatchedPath, OriginalUri},
    routing::get,
    Router,
};
async fn handle_nested(
    OriginalUri(original): OriginalUri,
    matched: Option<MatchedPath>,
) -> String {
    let matched_str = matched
        .as_ref()
        .map(|m| m.as_str())
        .unwrap_or("(no matched path)");
    format!(
        "Original URI: {}\nMatchedPath: {}",
        original, matched_str
    )
}
#[tokio::main]
async fn main() {
    let nested_routes = Router::new()
        .route("/users", get(handle_nested));
    let app = Router::new()
        .nest("/api/v1", nested_routes);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If you send a request to http://127.0.0.1:3000/api/v1/users?active=true, the handler responds:

Original URI: /api/v1/users?active=true
MatchedPath: /api/v1/users

MatchedPath shows the full route pattern, including the /api/v1 nest prefix - it is the pattern, not the stripped path. What it does not show is the query string: OriginalUri shows the full path and query string as the client sent it. This distinction is valuable for logging, building redirect URLs, or enforcing security rules based on the original request target.

Output Confirms Correct Understanding:

If you run the example above and see both the original URI (with the query string) and the matched path (the full pattern, prefix included), your handler is receiving the correct values. This contrast is exactly why OriginalUri exists.

Combining OriginalUri with Other Extractors

Because OriginalUri is a parts extractor, you can freely combine it with path parameters, query parameters, headers, and application state. The order of parts extractors does not matter for the result: none of them consume the body, so they can appear in any order.

Here is an example that extracts a path parameter, a query parameter, and the original URI together:

use axum::{
    extract::{OriginalUri, Path, Query},
    routing::get,
    Router,
};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
async fn handle_user(
    OriginalUri(original): OriginalUri,
    Path(user_id): Path<u32>,
    Query(pagination): Query<Pagination>,
) -> String {
    let page = pagination.page.unwrap_or(1);
    format!(
        "Original URI: {}\nUser ID: {}\nPage: {}",
        original, user_id, page
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/users/{user_id}", get(handle_user));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /users/42?page=2 produces:

Original URI: /users/42?page=2
User ID: 42
Page: 2

The presence of OriginalUri does not interfere with other extractors. Each extractor receives its own data independently from the request.

Accessing the Underlying Uri

OriginalUri is a tuple struct that wraps the http::Uri type. You can access the wrapped value by destructuring in the function parameter, as shown in all examples so far. Alternatively, you can access it through the .0 field:

async fn handler(original: OriginalUri) -> String {
    let uri: &http::Uri = &original.0;
    format!("The URI is: {}", uri)
}

The http::Uri type provides methods for inspecting its components: path(), query(), scheme(), authority(), etc. In origin-form URIs, scheme() and authority() typically return None.

use axum::extract::OriginalUri;
use axum::routing::get;
use axum::Router;
async fn inspect_uri(OriginalUri(uri): OriginalUri) -> String {
    let path = uri.path();          // "/some/path"
    let query = uri.query();        // Some("key=value")
    let scheme = uri.scheme();      // None for origin-form
    let authority = uri.authority(); // None for origin-form
    format!(
        "path: {}\nquery: {:?}\nscheme: {:?}\nauthority: {:?}",
        path, query, scheme, authority
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/some/{*path}", get(inspect_uri));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

If you visit http://127.0.0.1:3000/some/path?key=value, you'll see:

path: /some/path
query: Some("key=value")
scheme: None
authority: None

This confirms that the URI is stored in origin-form. To construct an absolute URL, you would need to combine this with the Host header or extractor.

Using OriginalUri for Redirects and Logging

A practical use case for OriginalUri appears when you need to redirect the client back to the same URL after some action, or when you want to log exactly what the client requested. Because OriginalUri stays stable through routing, it is ideal for these tasks.

Here's an example that redirects the client to the same URI but with an added query parameter. This pattern is often used to preserve the original request context when sending the user to a login page:

use axum::{
    extract::OriginalUri,
    response::{IntoResponse, Redirect},
    routing::get,
    Router,
};
async fn require_login(OriginalUri(uri): OriginalUri) -> impl IntoResponse {
    let redirect_uri = format!("/login?next={}", uri);
    Redirect::temporary(&redirect_uri)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/private", get(require_login));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When you visit /private?source=email, the server responds with a 307 Temporary Redirect to /login?next=/private?source=email. The original URI (including the query string) is embedded in the redirect target. (Redirect::temporary uses status 307, which preserves the request method - not 302.) In real code, percent-encode the embedded URI before putting it in a query value, so a ? or & inside the original request cannot break the redirect target apart.

This same technique is common in authentication middleware: capture the original URI before redirecting to a sign-in page, then return the user to that URI after successful login.

OriginalUri vs. MatchedPath and Path

Newcomers often confuse OriginalUri with MatchedPath and the path parameter extractor Path. All three deal with the request URI, but they represent different stages of routing.

  • OriginalUri - the full request URI exactly as the client sent it, before any routing transformations. It includes the query string and any nesting prefix.
  • MatchedPath - the path pattern that matched the handler, including any nest prefix, for example /api/v1/users for a route nested under /api/v1. It does not include the query string.
  • Path<T> - extracts and deserializes dynamic path parameters from the matched route. It is not concerned with the raw URI string at all.

Think of OriginalUri as the unprocessed input, MatchedPath as the post-routing pattern, and Path as specific pieces of data pulled from that pattern. They serve distinct purposes and should not be interchanged.

Do Not Use OriginalUri When You Only Need the Stripped Path:

If you only need the path after nesting stripped the prefix, use the Uri extractor instead - inside a nested router it sees the remaining path. If you need the route pattern, use MatchedPath. Using OriginalUri and then manually stripping prefixes is error‑prone because the original URI may contain query parameters, URL encoding, or other details you must handle.

What Can Go Wrong?

A few mistakes are common when first using OriginalUri.

Mistake 1: Assuming OriginalUri includes the host. Many developers expect OriginalUri to be an absolute URL like http://localhost:3000/api/users. It is not. In typical HTTP/1.1 requests, the request target is origin-form (/api/users). The host is sent separately in the Host header. If you need the absolute URL, extract both OriginalUri and Host and concatenate them.

Mistake 2: Expecting OriginalUri to change after routing. Some think that once Axum strips a nesting prefix, OriginalUri will also reflect that stripped path. That is false. OriginalUri is immutable and represents the initial request. If you want the path after the prefix was stripped, use the Uri extractor: inside a nested router it sees the remaining path, for example /users for a request to /api/v1/users. MatchedPath is not the stripped path either - it is the full matched pattern, prefix included.

Mistake 3: Trying to mutate the wrapped Uri. OriginalUri owns its http::Uri, but you cannot modify it and expect the rest of Axum to see the change. The extractor is read-only from the handler's perspective. If you need to alter the URI for downstream middleware, consider a different approach such as storing a modified URI in request extensions before the handler runs.

Mistake 4: Forgetting that OriginalUri includes the query string. When building redirects or logging, you must decide whether to preserve the query string. OriginalUri preserves it, which is usually what you want, but if you only need the path, use uri.path() to extract just that component.

Do Not Assume OriginalUri Is Always Present:

OriginalUri is always available inside handlers connected to the Axum router. However, if you are writing middleware that runs before Axum's router (e.g., a Tower layer outside the router), the original URI may not yet be stored in request extensions. In such middleware, use request.uri() directly, which returns the current URI of the request at that point. OriginalUri is specifically designed for handler extraction after routing has begun.

Extracting OriginalUri in Middleware

While this page focuses on using OriginalUri in handlers, you might encounter middleware that needs the original URI. In Axum, middleware layers often run after the router has stored the original URI, so you can access it via the request extensions. The OriginalUri extractor is not available directly in middleware because middleware uses the tower::Service trait, not Axum's handler extractors.

Instead, you can retrieve the stored original URI from request extensions:

use axum::{
    extract::OriginalUri,
    http::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
async fn log_original_uri(
    request: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if let Some(OriginalUri(uri)) = request.extensions().get::<OriginalUri>() {
        println!("Original URI in middleware: {}", uri);
    } else {
        println!("OriginalUri extension not found");
    }
    next.run(request).await
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello" }))
        .layer(middleware::from_fn(log_original_uri));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

When you send a request to /, the middleware prints the original URI before the handler runs. This works because Axum inserts an OriginalUri extension into the request parts at the start of routing.

This pattern is useful for logging or auditing at the middleware layer without modifying each handler. However, note that the extension is only present after the router begins processing. If you have middleware outside the router (applied via tower::ServiceBuilder before axum::serve), that middleware will not find the extension.

Complete Example with Nesting and Middleware

Let's combine everything into a single, runnable application that demonstrates OriginalUri in a nested router, with middleware logging the original URI. This example shows how the extractor behaves consistently across handlers and middleware.

use axum::{
    extract::OriginalUri,
    http::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
async fn log_middleware(
    request: Request<axum::body::Body>,
    next: Next,
) -> Response {
    if let Some(OriginalUri(uri)) = request.extensions().get::<OriginalUri>() {
        println!("Middleware sees original URI: {}", uri);
    }
    next.run(request).await
}
async fn nested_handler(OriginalUri(uri): OriginalUri) -> String {
    format!("Handler sees original URI: {}", uri)
}
#[tokio::main]
async fn main() {
    let nested = Router::new()
        .route("/items", get(nested_handler));
    let app = Router::new()
        .nest("/api/v1", nested)
        .layer(middleware::from_fn(log_middleware));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on 127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run this and send a request to http://127.0.0.1:3000/api/v1/items?sort=asc. You will see in the terminal:

Middleware sees original URI: /api/v1/items?sort=asc

And the HTTP response will be:

Handler sees original URI: /api/v1/items?sort=asc

Both the middleware and the handler receive the identical original URI. The nesting prefix is preserved, and the query string is included.

Summary

OriginalUri is a parts extractor that gives you the request URI exactly as it arrived at the server, before any routing modifications like prefix stripping in nested routers. It is invaluable when you need to log the real request target, build redirects back to the original URL, or enforce security rules based on the unmodified request.

The key insight is that OriginalUri remains stable throughout routing; it never changes. If you need the path after nesting stripped the prefix, use the Uri extractor. If you need the route pattern, use MatchedPath. If you need an absolute URL, combine OriginalUri with the Host extractor. Misunderstanding these distinctions leads to subtle bugs, so always confirm which URI representation your use case actually requires.

Once you understand OriginalUri, you are ready to explore more advanced routing techniques, such as path rewriting and nested routers with complex prefix handling. The extractor's behavior remains consistent across all those scenarios, making it a reliable tool for recording and acting on the client's true request.