Capturing Wildcard as Path String in Axum

Learn how to use the Path extractor to capture wildcard route segments as a String in Axum handlers, including detailed examples, URL decoding behavior, and common beginner mistakes.

When you define a route with a wildcard segment in Axum, you are telling the router: "match one or more path segments after this point." But matching alone is not enough. Your handler needs to actually get the value of that wildcard part so it can decide what file to serve, what resource to look up, or what action to take. That is exactly what this page covers: using the Path extractor to pull the wildcard portion out of the URL and receive it as a plain String in your handler function.

A wildcard is the {*name} segment at the end of a route pattern, written with braces in current Axum, for example /files/{*path}. It matches one or more path segments after a static prefix and hands the whole remainder to your handler as one value. Here, we focus entirely on the capture step -- turning the matched wildcard into data your code can actually use.

What "Capturing as Path String" Means

When a URL like /files/images/logo.png arrives at a route defined as /files/{*path}, Axum splits the path into two logical parts. The first part is the static prefix /files/, which the router matched literally. The second part is the wildcard portion: images/logo.png. That second part always contains at least one segment - the wildcard never matches an empty remainder, so /files/ and /files do not match this route at all.

The handler does not automatically receive this wildcard portion. You must explicitly ask for it by adding a parameter of type Path<String> (or with destructuring). The Path extractor then takes the matched wildcard value, percent-decodes it, and gives you the resulting String. That is what we mean by "capturing the wildcard as a path string."

Why a String?:

The wildcard can match multiple path segments, so it cannot be represented as a single numeric ID or a single word. A String is the natural container because the captured value can be arbitrary text like folder/subfolder/file.txt.

Setting Up a Basic Wildcard Capture Example

Before we dive into variations, let's build the smallest possible working program. This will show the entire flow: route definition, handler signature, and the output you should see when you make requests.

Create a new Rust project and add the required dependencies to Cargo.toml:

[package]
name = "axum-wildcard-capture"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1.0.229", features = ["derive"] }

Now replace src/main.rs with the following:

use axum::{
    extract::Path,
    routing::get,
    Router,
};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/files/{*path}", get(show_wildcard));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}
async fn show_wildcard(Path(path): Path<String>) -> String {
    format!("You requested: {}", path)
}

Let's understand what is happening here. The route pattern /files/{*path} tells Axum: after the literal /files/ prefix, capture everything else into a wildcard parameter named path. The handler show_wildcard takes one argument: Path(path): Path<String>. This is the standard pattern for extracting path parameters in Axum. The outer Path is the extractor type, and inside the parentheses we give a variable name. The inner type String tells Axum what Rust type to deserialize the path parameter into. Because the wildcard parameter is named path in the route, Axum matches it to this extractor automatically.

When you run this server and visit http://127.0.0.1:3000/files/hello/world.txt, the handler receives path = "hello/world.txt" and returns the string You requested: hello/world.txt.

Test your setup:

Start the server with cargo run and open a second terminal. Use curl to send a few requests:

  • curl http://127.0.0.1:3000/files/hello/world.txt → prints You requested: hello/world.txt
  • curl http://127.0.0.1:3000/files/ → 404 Not Found (the wildcard needs at least one segment)
  • curl http://127.0.0.1:3000/files/a → prints You requested: a

How the Path Extractor Finds the Wildcard Value

The Path extractor works by looking at the route definition and the incoming request URL together. When Axum matches a route, it records which parts of the URL correspond to which named parameters. For a wildcard like {*path}, the entire substring after the static prefix is treated as one value.

That value is then passed to the Path extractor, which behaves similarly to serde deserialization. For a Path<String>, Axum simply converts the raw matched string into a String. But there is an important detail: Axum automatically performs percent-decoding. If the incoming URL contains %20 (the encoded form of a space), the string you receive will contain an actual space character.

Consider this request:

GET /files/my%20documents/report.pdf HTTP/1.1

The wildcard portion as it appears in the raw URL is my%20documents/report.pdf. But inside your handler, path will be "my documents/report.pdf" -- the %20 has been decoded into a space. This is convenient because you usually want to work with human-readable names, but it's important to know if you later need to reconstruct the exact original URL.

Percent-decoding can change the value:

If your wildcard captures something that contains %2F (an encoded slash), Axum will decode it to /. That means %2F and / become indistinguishable in the extracted string. If you need to preserve the raw encoding, you would need to use the OriginalUri extractor, which is a different topic. For most use cases, the decoded behavior is what you want.

Capturing Wildcards with Static Prefixes in Realistic Scenarios

The basic example above used a route where the wildcard comes right after a static prefix. That is the most common pattern, often used to build file servers, proxy endpoints, or catch-all handlers for a subpath. Let's expand that into a more realistic handler that pretends to read a file from disk based on the captured path.

use axum::{
    extract::Path,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
async fn serve_file(Path(relative_path): Path<String>) -> Response {
    // Build a safe absolute path by joining with a base directory.
    // Canonicalize both paths first: a lexical starts_with check on the
    // raw joined path does NOT stop traversal ("../secret.txt" still
    // starts with "./public" as plain text).
    let base_dir = match std::env::current_dir()
        .unwrap()
        .join("public")
        .canonicalize()
    {
        Ok(p) => p,
        Err(_) => {
            return (StatusCode::INTERNAL_SERVER_ERROR, "Server misconfigured")
                .into_response()
        }
    };
    let requested = std::path::Path::new(&relative_path);
    let requested = requested.strip_prefix("/").unwrap_or(requested);
    let full_path = match base_dir.join(requested).canonicalize() {
        Ok(p) => p,
        Err(_) => return (StatusCode::NOT_FOUND, "File not found").into_response(),
    };
    // Prevent path traversal attacks by ensuring the final path stays inside base_dir.
    if !full_path.starts_with(&base_dir) {
        return (StatusCode::FORBIDDEN, "Access denied").into_response();
    }
    // For this example, just check if the file exists.
    if full_path.is_file() {
        let content = std::fs::read_to_string(&full_path)
            .unwrap_or_else(|_| "File exists but could not be read".to_string());
        (StatusCode::OK, content).into_response()
    } else {
        (StatusCode::NOT_FOUND, "File not found").into_response()
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/public/{*path}", get(serve_file));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Before running this, create a public directory in your project root with a file inside it, for example public/hello.txt. The handler resolves that directory with canonicalize() at the start of every request, so if the directory is missing you get a 500 Server misconfigured response instead of a file listing.

In this version, the handler receives the wildcard as relative_path and then uses std::path::Path to safely construct a filesystem path. The wildcard is never empty - a request to /public/ does not match the route at all (404), so there is no empty-string case to handle here.

Notice that the route now uses /public/{*path}. This is the same wildcard capture principle but with a different static prefix. The captured string does not include the /public/ part; it only contains what comes after it, such as images/logo.png or css/main.css.

There Is No Empty Wildcard Match

The empty-match rule directly affects what your Path<String> receives, so it is worth stating plainly here. A wildcard never matches an empty remainder: a request to /files/ (with a trailing slash) does not match the route at all and returns 404. There is no empty string for your handler to receive, so do not write branches for path.is_empty() in a wildcard handler - they can never run.

What can happen is a capture that is only slashes. Because Axum does not normalize repeated slashes in the request path:

  • Request /files/ → 404 (no match)
  • Request /files// → wildcard is / (one slash)
  • Request /files/// → wildcard is // (two slashes)

If your handler treats the wildcard as a filesystem path, a capture of / or // resolves to the base directory itself (after canonicalization), which is not a file - so a file-serving handler should return 404 for it. Test your handler with these edge cases to make sure it behaves as expected.

Trailing slashes matter:

A trailing slash at the end of the URL changes what the wildcard captures - or whether it matches at all. /files/ does not match, while /files// matches with a capture of /. This can cause subtle bugs if you are joining paths without normalizing them.

Combining the Path Extractor with Other Extractors

One of the strengths of Axum is that you can combine multiple extractors in a single handler. The wildcard Path<String> works alongside Query, State, HeaderMap, and many others. The only restriction is that extractors consuming the request body (like Json or Form) must appear last. Path is a "from parts" extractor, so it can be placed early.

Here is an example that also extracts a query parameter and application state:

use axum::{
    extract::{Path, Query, State},
    routing::get,
    Router,
};
use serde::Deserialize;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    base_dir: String,
}
#[derive(Deserialize)]
struct Pagination {
    page: Option<u32>,
}
async fn list_directory(
    State(state): State<Arc<AppState>>,
    Path(relative_path): Path<String>,
    Query(pagination): Query<Pagination>,
) -> String {
    let page = pagination.page.unwrap_or(1);
    format!(
        "Listing {} in {} - page {}",
        relative_path, state.base_dir, page
    )
}
#[tokio::main]
async fn main() {
    let state = Arc::new(AppState {
        base_dir: "/srv/files".to_string(),
    });
    let app = Router::new()
        .route("/browse/{*path}", get(list_directory))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Notice the order of parameters: State first, then Path, then Query. This order is not strict for these three, but it is conventional to put state first, then path, then query. The wildcard path is available as relative_path exactly as before. The serde dependency in the Cargo.toml above is what makes the Pagination struct work - Query needs Deserialize to parse the query string into it.

What About Capturing Multiple Segments as a Vector?

You might wonder whether it is possible to capture the wildcard directly as a Vec<String> where each segment is a separate element. Path<Vec<String>> does compile and run - but it does not split the capture: it gives you a one-element vector holding the whole captured string, e.g. ["a/b/c"] for a request to /tree/a/b/c.

If you need individual segments, split the string yourself inside the handler:

use axum::{extract::Path, routing::get, Router};
async fn handle(Path(path): Path<String>) -> String {
    let segments: Vec<&str> = path.split('/').collect();
    format!("Number of segments: {}", segments.len())
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/tree/{*path}", get(handle));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

A request to /tree/a/b/c prints Number of segments: 3. This gives you full control. (And since the wildcard always captures at least one segment, the string you split is never empty.)

Common Mistakes and How to Fix Them

Working with wildcards and the Path extractor has a few sharp edges that trip up beginners. Let's look at each one and how to avoid it.

Forgetting the Path Extractor

If you define a route with {*path} but your handler does not include a Path parameter, Axum will still match the route, but the wildcard value is simply ignored. This is not an error -- Axum does not force you to consume every path parameter. However, if you need the value, you must add the extractor.

// Route matches, but wildcard is discarded
async fn handler() -> String {
    "Hello".to_string()
}

If you forget the extractor, you won't get a compile error; the handler just won't receive the path. This can be confusing when debugging.

Using the Wrong Type

The most common type for wildcard capture is Path<String>. Some beginners try Path<&str>, which does not work because the extractor needs an owned String to return. Stick with String or a custom type that implements serde::Deserialize if you want to parse the captured string further.

Expecting the Leading Slash

The captured wildcard does not include the leading slash of the wildcard portion. For route /files/{*path} and request /files/hello, the value of path is "hello", not "/hello". If you join this with a base path that expects a relative path, this is usually what you want. But if you try to use it as a URL path directly, you'll need to add the slash yourself.

Ignoring Percent-Decoding

As mentioned earlier, Axum decodes percent-encoded characters automatically. This is usually helpful, but if you are logging the original URL or comparing hashes, you might be surprised that %2F became /. Keep this in mind when your handler needs the exact raw string.

Path traversal risk:

When you use the captured wildcard to construct filesystem paths, you must sanitize it. A user can send ../../etc/passwd as the wildcard. If you naively join it with a base directory, you could read files outside that directory. Always check that the final path remains inside your intended root, as shown in the earlier serve_file example.

A Complete File-Serving Example with Wildcard Capture

Let's put together a slightly more complete example that serves static files from a directory while using the wildcard to specify the relative path. This example includes error handling and demonstrates how the wildcard interacts with a real filesystem.

First, create a directory named public in your project root and place some files inside it, for example public/hello.txt and public/images/logo.png.

Now write the full src/main.rs:

use axum::{
    extract::Path,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use tokio::fs;
async fn serve_from_public(Path(relative_path): Path<String>) -> Response {
    let base_dir = match std::env::current_dir()
        .unwrap()
        .join("public")
        .canonicalize()
    {
        Ok(p) => p,
        Err(_) => {
            return (StatusCode::INTERNAL_SERVER_ERROR, "Server misconfigured")
                .into_response()
        }
    };
    // Reject path traversal attempts. Canonicalize first: a lexical
    // starts_with check on the raw joined path does not stop "../secret.txt".
    let requested = std::path::Path::new(&relative_path);
    let requested = requested.strip_prefix("/").unwrap_or(requested);
    let requested_path = match base_dir.join(requested).canonicalize() {
        Ok(p) => p,
        Err(_) => return (StatusCode::NOT_FOUND, "File not found").into_response(),
    };
    if !requested_path.starts_with(&base_dir) {
        return (StatusCode::FORBIDDEN, "Forbidden").into_response();
    }
    match fs::read(&requested_path).await {
        Ok(contents) => {
            // Determine a rough MIME type based on extension (simplified)
            let mime = mime_guess::from_path(&requested_path)
                .first_or_octet_stream();
            (
                StatusCode::OK,
                [(axum::http::header::CONTENT_TYPE, mime.as_ref())],
                contents,
            )
                .into_response()
        }
        Err(_) => (StatusCode::NOT_FOUND, "File not found").into_response(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/static/{*path}", get(serve_from_public));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Serving files on http://127.0.0.1:3000/static/");
    axum::serve(listener, app).await.unwrap();
}

For this example to compile, you also need to add mime_guess to Cargo.toml:

[dependencies]
axum = "0.8.9"
tokio = { version = "1.54.1", features = ["full"] }
serde = { version = "1.0.229", features = ["derive"] }
mime_guess = "2"

Now test it:

  • curl http://127.0.0.1:3000/static/hello.txt → serves the file content.
  • curl http://127.0.0.1:3000/static/images/logo.png → serves the image.
  • curl http://127.0.0.1:3000/static/../secret.txt → returns 403 Forbidden because the path escapes the public directory.

This example shows how the wildcard capture can be used in a real-world scenario and why the security check is essential.

Summarizing the Key Ideas

The topic of capturing a wildcard as a path string is deceptively simple on the surface but carries important details. The Path extractor is the bridge between the router's wildcard match and your handler's logic. It gives you a decoded String containing everything after the static prefix, including any internal slashes. You must remember that the string is never empty (the route does not match without at least one segment), that it does not include a leading slash, and that percent-encoding has already been resolved.

When you combine this extractor with other extractors, you keep the same pattern: Path(name): Path<String> as one of the handler's parameters. And whenever that captured string influences filesystem access, treat it as untrusted input and validate it carefully.

This understanding will directly carry forward when you build more advanced handlers that need to interpret dynamic URL paths, such as API versioning, file downloads, or nested resource routing. The ability to reliably receive whatever a user put after a slash is a foundational skill in Axum.