What is the right way to serve a dir and handle 404 with axum?

 let app: Router = Router::new()
             .nest_service("/", get_service(svc: ServeDir::new(path: "./public")))
             .route("/lists", get(handler))
             .route("/markdown/:name", get(handler_md))
             .fallback(handler_404);

the above fallback is not working.

Try something like :

let fallback_service = ServeDir::new(&assets)
        .not_found_service(handler_404.into_service());

let app = Router::new()
    // your routes
    .fallback_service(fallback_service)

If you need your state inside your 404_handler try this instead.

let fallback_service = ServeDir::new(&assets)
        .not_found_service(Handler::with_state(handler_404, state.clone()));

I've migrated to poem, not just because of this issue.

My front end is spa, your code can handle the path not found, but it also shows not found when the non-home page is refreshed.

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.