expression
Axum: serve a public asset directory
ServeDir exposes a configured public directory. Nesting it under /assets maps requests under that URL prefix to the directory. Use a dedicated immutable public asset tree with no private uploads or secrets; do not assume the service is a sandbox for untrusted filesystem contents. Standalone Cargo example: execute only in a fresh isolated scratch directory. Expected stdout (not executed): 200 hello Common mistake: Serving a project root or private upload directory as public static files.
Formal Syntax & Structure
rust syntaxrust
Router::new().nest_service("/assets", ServeDir::new("public"))Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use tower_http::services::ServeDir; std::fs::create_dir("v73-public-demo").unwrap(); std::fs::write("v73-public-demo/hello.txt", "hello").unwrap(); let app = Router::new().nest_service("/assets", ServeDir::new("v73-public-demo")); let r = app.oneshot(Request::builder().uri("/assets/hello.txt").body(Body::empty()).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); let data = to_bytes(r.into_body(), 64).await.unwrap(); println!("{}", String::from_utf8_lossy(&data));}