Answer#
ServeDir::new(folder) serves files below one folder. Use fallback_service so API routes are matched first:
use axum::{body::{to_bytes, Body}, http::{header, Request}, routing::get, Router};
use tower::ServiceExt;
use tower_http::services::{ServeDir, ServeFile};
#[tokio::main]
async fn main() {
// A scratch folder with two files, plus one secret file next to it.
let base = std::env::temp_dir().join("rs-static-demo");
let public = base.join("public");
std::fs::create_dir_all(&public).unwrap();
std::fs::write(public.join("index.html"), "<h1>home</h1>").unwrap();
std::fs::write(public.join("app.css"), "body { margin: 0 }").unwrap();
std::fs::write(base.join("secret.txt"), "not for the web").unwrap();
// Files come from `public`; an unknown path gets index.html (with status 404 here).
let files = ServeDir::new(&public).not_found_service(ServeFile::new(public.join("index.html")));
let app = Router::new().route("/api/ping", get(|| async { "pong" })).fallback_service(files);
for uri in ["/", "/app.css", "/api/ping", "/no/such/page", "/%2e%2e/secret.txt", "/../secret.txt"] {
let res = app.clone().oneshot(Request::get(uri).body(Body::empty()).unwrap()).await.unwrap();
let status = res.status().as_u16();
let ctype = res.headers().get(header::CONTENT_TYPE).map(|v| v.to_str().unwrap().to_string());
let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
println!("{uri} -> {status} {ctype:?} {:?}", String::from_utf8_lossy(&body));
}
}/ -> 200 Some("text/html") "<h1>home</h1>"
/app.css -> 200 Some("text/css") "body { margin: 0 }"
/api/ping -> 200 Some("text/plain; charset=utf-8") "pong"
/no/such/page -> 404 Some("text/html") "<h1>home</h1>"
/%2e%2e/secret.txt -> 404 Some("text/html") "<h1>home</h1>"
/../secret.txt -> 404 Some("text/html") "<h1>home</h1>"/servedindex.html, and/app.cssgottext/cssfrom its extension./api/pingis a normal route and was never looked up as a file.- An unknown path got the
index.htmlcontent with status 404, fromnot_found_service. That is right for a plain site; a single-page app whose router handles paths in the browser may want 200 instead, so check what your front-end needs. - Both attempts to reach
secret.txtin the parent folder (%2e%2eand..) failed with 404; the file service did not leave its folder.
tower-http = { version = "0.6.11", features = ["fs"] }Common mistakes#
- Pointing
ServeDirat the project root. Everything in it (source,.env) becomes downloadable; serve a dedicatedpublicfolder. - Relative folder paths: they depend on where the program is started. Build the path from a configured base or from
current_exe.
Related questions#
How do I serve the folder under a prefix such as /assets?#
Use nest_service("/assets", ServeDir::new("public")).
Sources#
- tower-http,
ServeDir: https://docs.rs/tower-http/0.6.11/tower_http/services/struct.ServeDir.html (read 2026-12-05)