ServeDir - Serving Files from a Folder
Learn what a static file is and how ServeDir from tower-http serves a whole folder of files through an Axum server
A static file is a file that already exists on disk and is sent to the browser exactly as it is stored. An HTML page, a stylesheet, a script, an image, and a font are all static files. The server does not run code to build them and does not change their contents per visitor. It reads the file and sends the bytes back. ServeDir is the ready-made piece of the tower-http crate that does this job for a whole folder at once. You point it at a directory, mount it in your Axum application, and every file inside that directory becomes reachable over HTTP.
Where This Fits
Until now, every response in this course has been produced by a handler function that built its answer in code. That works well for JSON and for pages that change per request. It is the wrong tool when the answer already sits on disk as a file. Writing one handler per file would mean a new route for every image, stylesheet, and page, plus manual code to read the file, pick the right content type, and handle missing files. ServeDir replaces all of that with one service that maps request paths to files on disk.
Think of it like a librarian with a key to one room. A visitor asks for a book by name, the librarian walks into the room, finds the matching shelf, and hands the book over unchanged. The librarian never rewrites the book and never guesses which book you meant. ServeDir works the same way with files.
The Smallest Working Version
Create a project with this layout. The assets folder holds the files to serve, and src/main.rs holds the server.
my-site/
Cargo.toml
src/main.rs
assets/
index.html
style.css
The Cargo.toml file needs three dependencies. tower-http needs the fs feature turned on, because file serving lives behind that feature flag. A feature flag is an on-off switch inside a crate that selects which parts of the crate get compiled.
[package]
name = "my-site"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }
The HTML file is a plain page that links to the stylesheet. The link uses the path /style.css, which is the same path the server will expose.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Welcome to my site</h1>
<p>This page was served from a file on disk.</p>
</body>
</html>
The stylesheet is one rule. It exists so you can see a second file type being served with its own content type.
body {
color: navy;
font-family: sans-serif;
}
The server itself is short. ServeDir::new("assets") builds the service, and fallback_service mounts it so that any request no route matched is handed to it.
use axum::Router;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
let app = Router::new().fallback_service(ServeDir::new("assets"));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run, then open http://127.0.0.1:3000 in a browser. The page appears, styled in navy text, because the browser asked for / and then for /style.css, and the server answered both from disk. The same check works from the terminal with curl, a command line tool that makes HTTP requests and prints the response.
curl http://127.0.0.1:3000/
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My Site</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Welcome to my site</h1>
<p>This page was served from a file on disk.</p>
</body>
</html>
Asking for the stylesheet directly shows its contents, and the -i flag asks curl to print the response headers as well as the body.
curl -i http://127.0.0.1:3000/style.css
HTTP/1.1 200 OK
content-type: text/css
accept-ranges: bytes
last-modified: Sat, 14 Nov 2026 10:06:50 GMT
etag: "6af832ba.1ef0834f-16"
content-length: 22
date: Sat, 14 Nov 2026 10:08:04 GMT
body {
color: navy;
font-family: sans-serif;
}
Working Setup:
If the browser shows the page and curl returns the stylesheet with a 200 OK status and a content-type: text/css header, the folder is being served correctly.
How the Request Path Becomes a File Path
The core idea of ServeDir is a mechanical mapping between two paths. The request path from the URL is appended to the folder path given to ServeDir::new, and the result is the file that gets read. A request for /style.css against ServeDir::new("assets") opens assets/style.css. A request for /docs/guide.html opens assets/docs/guide.html, including files in subfolders. Nothing else happens to the path. There is no routing table to configure and no handler to write per file. Adding a new file to the folder makes it reachable immediately, with no code change and no server restart.
Two details of this mapping deserve attention because beginners trip over them. First, the folder path is relative to the directory the server process starts in, not to the src folder or to the crate root in any absolute sense. When you run cargo run from the project root, the working directory is the project root, so "assets" means the assets folder next to Cargo.toml. If you start the compiled binary from a different directory, the same relative path points somewhere else, and every request returns a 404. Second, the request path / maps to the folder itself rather than to a file. That case is handled by the index file behaviour, where a request for a directory serves the index.html file inside it. That is why the browser request for / returned the contents of assets/index.html.
fallback_service is the method that mounts the service at the root of the application. A fallback is what runs when nothing else matched. Since the router in the example has no routes at all, every request falls through to ServeDir. The service then decides, per request, whether a matching file exists.
What ServeDir Is Under the Hood
A service is a value that takes a request and produces a response. Handlers are one way to build responses, and a service is the lower-level shape underneath them. ServeDir is a service that someone else already wrote, tested, and packaged: it reads a file from disk, wraps the bytes in a response, and sets the headers a browser expects. Axum accepts any service as a mount point, which is why fallback_service can take a ServeDir directly.
The mental model that keeps this straight is a vending machine for files. You put a folder in, and each request is a button press naming a file. The machine either drops the file out or flashes an empty slot. It never cooks anything fresh. That is the difference between static serving and a handler: a handler is a kitchen that prepares a response on the spot, while ServeDir is a shelf that hands over what is already there.
Why a Ready-Made Service Beats One Handler Per File
A beginner's first instinct is often to write a handler that reads a file and returns it, then copy that handler for each file. That approach breaks in three places. The content type must be set by hand for every file type, and a wrong guess makes the browser mishandle the file. Missing files need an explicit check, or the handler panics and the request fails instead of returning a clean 404. And every new file needs a new route, so the route list grows with the folder.
ServeDir solves all three. It guesses the content type from the file extension. It returns a clean empty 404 for a missing file. And it serves any file in the folder with no per-file configuration. The service also adds behaviour a hand-written handler usually misses: HEAD requests, byte-range requests for resuming downloads and streaming video, Last-Modified and ETag headers that let browsers cache files, and protection against path tricks that try to escape the folder. Each of those is covered in its own section below.
A Richer Example - a Small Documentation Site
Real sites have more than two files. This example grows the folder into a small documentation site with a subfolder, a script, an image, and a JSON data file. The server code does not change at all, which is the point: the folder is the configuration.
assets/
index.html
style.css
app.js
logo.png
data.json
docs/
index.html
guide.html
The files themselves can be small. What matters is that each has a different extension, so you can watch the content type change per file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Docs Home</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Docs Home</h1>
<p>Read the <a href="/docs/guide.html">guide</a>.</p>
<img src="/logo.png" alt="Logo">
<script src="/app.js"></script>
</body>
</html>
console.log("hello from app.js");
{"name": "demo"}
<h1>Guide</h1>
<p>This file lives in a subfolder.</p>
The server is the same main.rs as before. Run it and request each file. The script, the image, the JSON file, and the subfolder page all come back with a 200 status and the content type that matches the extension: text/javascript for .js, image/png for .png, application/json for .json, and text/html for .html files in subfolders. The browser request for the home page triggers four more requests on its own - the stylesheet, the script, the image, and the guide link - and all four are answered from the same folder.
The Folder Is the Configuration:
When a site is served this way, adding a page means adding a file. Removing a page means deleting a file. No route is registered, no code is edited, and the server does not need to restart. That is the main practical payoff of static serving.
What the Browser Receives Besides the File
A response carries headers as well as a body, and ServeDir sets several that matter. The content-type header tells the browser what kind of data the body is, so it knows whether to render a page, apply a stylesheet, run a script, or show an image. ServeDir guesses this from the file extension, and the guessing rules have their own page later in this chapter. The accept-ranges: bytes header announces that the server supports byte-range requests. last-modified records when the file last changed on disk. The etag header is a short fingerprint built from the file size and modification time. Together, last-modified and etag let a browser ask "has this file changed since I last downloaded it?" and skip re-downloading when the answer is no.
None of these headers need configuration. They appear because the service sets them on every file response. When you inspect a response with curl -i, seeing them is a good sign that the file is being served by ServeDir and not by a hand-rolled handler that forgot them.
Missing Files and the Empty 404
Asking for a file that does not exist returns a 404 with an empty body. The status code is the whole answer: 404 means "not found" in HTTP, and the empty body means ServeDir does not invent a pretty error page on its own.
curl -i http://127.0.0.1:3000/missing.txt
HTTP/1.1 404 Not Found
content-length: 0
date: Sat, 14 Nov 2026 10:08:04 GMT
This behaviour is deliberate. A file server cannot know what your error page should look like, so it sends the status and lets you decide. If you want a custom page for missing files, that is a configuration of this same service, and it belongs to the fallback technique used for single-page apps.
An Empty 404 Is Not a Broken Server:
Beginners sometimes see the empty 404 and assume the server failed to start or the mount is wrong. Check the status code first. A 404 means the server is running and the service is mounted, but the file is not in the folder. A connection error, by contrast, means nothing is listening at all.
Directories and the Trailing Slash Redirect
Requesting a directory path, such as /docs/, serves the index.html file inside that directory. Requesting the same directory without the trailing slash, /docs, returns a redirect instead. The redirect is a 307 Temporary Redirect with a location header pointing at /docs/, and the browser follows it automatically before requesting the file.
curl -i http://127.0.0.1:3000/docs
HTTP/1.1 307 Temporary Redirect
location: /docs/
content-length: 0
date: Sat, 14 Nov 2026 10:08:11 GMT
The redirect exists because relative links inside a page resolve differently depending on whether the page URL ends with a slash. A page served at /docs that links to guide.html would resolve that link to /guide.html, which is wrong. Served at /docs/, the same link resolves to /docs/guide.html, which is right. The redirect keeps relative links working. Both the redirect and the index file behaviour are defaults that can be changed with methods on ServeDir, and the index file behaviour is covered in full on its own page.
What ServeDir Refuses to Serve
A file server that follows any path a client sends would be a security hole, because a request for ../secret.txt could escape the folder. ServeDir blocks several such tricks and answers each with a 404. Any path segment containing .. is rejected, including the URL-encoded form %2e%2e, which the server decodes and then rejects. Any segment containing a backslash is rejected. A path that treats a file as a directory, such as /style.css/anything, is rejected. And a file the server process has no permission to read is answered with a 404 rather than leaking the fact that the file exists.
curl -i --path-as-is http://127.0.0.1:3000/../Cargo.toml
HTTP/1.1 404 Not Found
content-length: 0
date: Sat, 14 Nov 2026 10:08:13 GMT
The --path-as-is flag stops curl from cleaning up the .. before sending it, so the server sees the attack exactly as written. The 404 proves the escape failed. This protection is built in, not something you configure. It is also why serving a folder is safer than writing your own handler that joins the request path onto a folder path with no checks.
Never Build File Paths from Request Paths by Hand:
Joining a request path onto a folder with plain string or path code and then opening the result is the classic directory traversal bug. ServeDir already does the joining with checks. If you ever need custom file logic, keep the checks: reject .., reject backslashes, and confirm the final path still sits inside the intended folder.
Only GET and HEAD, Plus Range Requests
ServeDir answers GET and HEAD requests. GET returns the file. HEAD returns the same headers without the body, which is how a client checks whether a file exists or how large it is before downloading. Any other method, such as POST, is rejected with 405 Method Not Allowed and an allow header listing the permitted methods.
curl -i -X POST http://127.0.0.1:3000/style.css
HTTP/1.1 405 Method Not Allowed
allow: GET,HEAD
content-length: 0
date: Sat, 14 Nov 2026 10:08:13 GMT
A file server that accepted POST would have to decide what a posted body means for a file, and ServeDir refuses to guess. Uploads belong to a different mechanism entirely.
Range requests are the other half of this section. A client can ask for only part of a file with a Range header, and the server answers with 206 Partial Content and a content-range header describing which bytes were sent.
curl -i -H "Range: bytes=0-4" http://127.0.0.1:3000/style.css
HTTP/1.1 206 Partial Content
content-type: text/css
accept-ranges: bytes
last-modified: Sat, 14 Nov 2026 10:06:50 GMT
etag: "6af832ba.1ef0834f-16"
content-range: bytes 0-4/22
Ranges are what make video seeking and resumable downloads work. A media player asks for the middle of a file instead of downloading from the start, and the browser resumes an interrupted download by asking for the remaining bytes. Both work out of the box because the accept-ranges header and the range handling are built into the service.
Serving a Precompressed Copy
Some files have a compressed twin sitting next to them, such as app.js.gz next to app.js. The .gz file is the same JavaScript squeezed with gzip, a compression format that makes text files much smaller on the wire. ServeDir can serve the compressed twin when the client says it accepts gzip, and fall back to the plain file otherwise. Both files must exist in the folder: the plain file is the fallback, and the compressed file is used only when it is present and the client asks for it.
use axum::Router;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
let app = Router::new()
.fallback_service(ServeDir::new("assets").precompressed_gzip());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
The .gz file is created once, outside the server, with the gzip command. The -k flag keeps the original file alongside the compressed one.
gzip -kf assets/app.js
A client that sends Accept-Encoding: gzip receives the compressed file with a content-encoding: gzip header, and the browser decompresses it before running the script. The content type stays text/javascript, because the file is still JavaScript, only squeezed. A client that does not accept gzip, or a file with no .gz twin, gets the plain file as before.
curl -i -H "Accept-Encoding: gzip" http://127.0.0.1:3000/app.js
HTTP/1.1 200 OK
content-type: text/javascript
accept-ranges: bytes
content-encoding: gzip
vary: accept-encoding
last-modified: Sat, 14 Nov 2026 10:06:50 GMT
etag: "6af832ba.1ef0834f-31"
content-length: 49
The vary: accept-encoding header warns caches that the response depends on what the client accepts, so a cache does not hand the gzipped bytes to a client that cannot decompress them. ServeDir also offers precompressed_br for Brotli files ending in .br, precompressed_deflate for files ending in .zz, and precompressed_zstd for files ending in .zst. Each works the same way: the compressed twin must already exist in the folder.
How a Request Flows Through ServeDir
The full path of a request through the service, from the browser to the disk and back, looks like this in plain text.
Browser asks for /docs/guide.html
|
v
Router has no matching route, so the request falls through
|
v
ServeDir joins the folder path and the request path
assets + /docs/guide.html = assets/docs/guide.html
|
v
Path checks run: no "..", no backslash, no file used as a directory
|
v
The path is a file, so it is opened and read
|
v
Content type is guessed from the .html extension: text/html
|
v
Response sent with 200 OK, headers, and the file bytes
A request for a missing file leaves this flow at the open step and returns the empty 404 instead. A request for a directory leaves the flow at the join step and is handled by the index file behaviour or the trailing slash redirect.
Testing It
A static file service can be tested without starting a real server. The tower crate's ServiceExt trait adds an oneshot method that sends a single fake request straight through a Router and returns the response. That is the same testing shape used for handlers, applied to a whole mounted service.
use axum::{body::Body, http::{Request, StatusCode}, Router};
use tower::ServiceExt;
use tower_http::services::ServeDir;
fn app() -> Router {
Router::new().fallback_service(ServeDir::new("assets"))
}
#[tokio::test]
async fn serves_css_with_text_css() {
let response = app()
.oneshot(
Request::builder()
.uri("/style.css")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/css");
}
#[tokio::test]
async fn missing_file_is_empty_404() {
let response = app()
.oneshot(
Request::builder()
.uri("/nope.txt")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
}
The tests build the same application the server runs, then make requests against it in memory. The first test proves a real file is served with the right content type. The second proves a missing file returns 404. The tower crate is needed as a dev dependency, and it needs the util feature for oneshot.
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the tests with cargo test. Both pass. One detail worth knowing: the tests run with the crate root as the working directory, so ServeDir::new("assets") finds the same folder the server finds when started with cargo run.
Common Beginner Mistakes
Running the Server from the Wrong Directory
# Wrong - started from inside src/, so "assets" does not exist there
cd src && cargo run --manifest-path ../Cargo.toml
Every request returns 404, even though the files exist and the code is right. The folder path is relative to the working directory, so starting the process elsewhere moves the folder it looks in. The fix is to start the server from the project root, or to pass an absolute path to ServeDir::new. When every file 404s at once, check the working directory before doubting the code.
Every File 404s at Once:
A single missing file means the file is not in the folder. Every file missing at once almost always means the working directory is wrong and the folder itself was not found. Run pwd in the terminal where the server started and compare it with where the assets folder lives.
Forgetting the fs Feature
# Wrong - ServeDir does not exist without the fs feature
tower-http = "0.7"
The compiler reports that ServeDir cannot be found in tower_http::services. File serving is behind the fs feature flag, and without it the name does not exist at all. The fix is the dependency line from the smallest example: tower-http = { version = "0.7", features = ["fs"] }.
Passing ServeDir to route as if It Were a Handler
// Wrong - ServeDir is a service, not a handler, so route() rejects it
let app = Router::new().route("/", get(ServeDir::new("assets")));
route expects a handler function, and ServeDir is a service, so this does not compile. Services are mounted with methods made for them: fallback_service for the root, as in this page. Mounting the same folder under a path prefix, serving an index file for directory requests, and falling back to index.html for single-page apps are separate techniques built on this same service.
Expecting a Directory Listing
Requesting /docs/ does not produce a list of the files in docs. ServeDir never lists directory contents. It serves the index.html inside the directory, or returns 404 when there is none. A listing page, if you want one, is something you build yourself as a real HTML file or a handler.
Putting the Files Inside src
Serving the src folder technically works, but it exposes your Rust source code over HTTP to anyone who guesses a filename. Keep served files in a dedicated folder such as assets or static, separate from code.
Final Complete Example
Here is everything from this page put together: a documentation site with a home page, a stylesheet, a script, an image, a JSON file, a subfolder of pages, and precompressed JavaScript. The server code is one mount with one option.
use axum::Router;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
let app = Router::new()
.fallback_service(ServeDir::new("assets").precompressed_gzip());
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
assets/
index.html
style.css
app.js
app.js.gz
logo.png
data.json
docs/
index.html
guide.html
[package]
name = "my-site"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run it, then check the behaviours from this page in order: the home page at /, the stylesheet with text/css, the script served compressed when gzip is accepted, the guide at /docs/guide.html, the redirect from /docs to /docs/, and the empty 404 for a missing file. Each one is the same service doing the same path mapping, with a different file or a different edge case.
Summary
The single most important insight is that static serving is a mapping, not a program. A request path names a file, the folder supplies the file, and the response is the file itself plus a few headers. Everything ServeDir adds around that mapping exists to keep the mapping honest: content types so the browser treats each file correctly, 404s for missing files, redirects so relative links resolve, range support so media and downloads work, and path checks so a client cannot escape the folder.
That mapping shape also tells you when ServeDir is the wrong tool. If the response must be built per request, per user, or per database row, a handler is the answer, because no file on disk holds the response. If the file must travel inside the binary instead of living in a folder next to it, embedding is a different technique. And if the same folder must answer under a path prefix such as /static while the rest of the application stays an API, the mount point changes, not the service. In each case the question to ask is the same: does a file on disk already hold the answer, and which path should name it?