FAQ - Help and questions

How do I serve static files and an index page from axum?

#axum#static-files#tower-http#spapublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Use tower-http ServeDir as the router fallback service so that real routes win and every other path is looked up in a folder. It sets the content type from the file extension, refuses paths that climb out of the folder, and can fall back to index.html with not_found_service.

Checked with rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot; tower-http 0.6.11; the program creates its own scratch folder

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

ServeDir::new(folder) serves files below one folder. Use fallback_service so API routes are matched first:

src/main.rsrust
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));
    }
}
text
/ -> 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>"
  • / served index.html, and /app.css got text/css from its extension.
  • /api/ping is a normal route and was never looked up as a file.
  • An unknown path got the index.html content with status 404, from not_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.txt in the parent folder (%2e%2e and ..) failed with 404; the file service did not leave its folder.
Cargo.tomltoml
tower-http = { version = "0.6.11", features = ["fs"] }

Common mistakes#

  • Pointing ServeDir at the project root. Everything in it (source, .env) becomes downloadable; serve a dedicated public folder.
  • Relative folder paths: they depend on where the program is started. Build the path from a configured base or from current_exe.

How do I serve the folder under a prefix such as /assets?#

Use nest_service("/assets", ServeDir::new("public")).

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet