Axum match pattern failing to nest and route service

I have to do like this in Axum.

let router = Router::new()
            .nest_service("/", /* capture all "/*" routes and forward it one service */*/some())
            .route_service("/", /* just check this / and forward it another service */another())

I honestly expected it to happen like I described, nut, its just throwing route already registered error. What should I do?

You need to add a wildcard to your nested service. According to the docs for Axum's Router:

Paths can end in /*key which matches all segments and will store the segments captured at key.

Note that /*key doesn’t match empty segments. Thus:

  • /*key doesn’t match / but does match /a, /a/, etc.

No, nested service will not support wildcards. Here's the error:

thread 'main' panicked at ~/.cargo/registry/src/
Invalid route: nested routes cannot contain wildcards (*)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

In that case, you can try changing the nest_service() to fallback_service(), and this will capture all routes not already matched.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.