ServeDir Index File - Serving index html for Directory Requests

Learn how ServeDir serves index html when a request names a directory and how append_index_html_on_directories controls that behaviour

When a browser asks for a directory instead of a file, ServeDir answers with a file named index.html from inside that directory. A request for / serves assets/index.html. A request for /docs/ serves assets/docs/index.html. The file is called the index file, and the behaviour is controlled by one method: append_index_html_on_directories. It is on by default, which is why the examples on the earlier pages worked without any configuration. This page explains exactly what the method does, what happens when it is turned off, and how it interacts with the trailing slash redirect.

Where This Fits

The earlier pages showed ServeDir serving files by path, and the root request / returning the home page. That home page was not magic. It was the index file behaviour doing its job silently. A URL that names a folder has no file to serve, so the service appends index.html to the path and serves that file instead. Understanding this one rule explains three things you have already seen: why / returns a page, why /docs/ returns a page, and why a folder with no index.html returns a 404. It also explains the difference between a folder URL and a file URL, which matters for every static site.

Think of it like the front desk of an apartment building. You ask for the building, and the desk hands you the lobby directory instead of a specific apartment. The lobby directory is the index.html: the file that represents the folder itself.

The Smallest Working Version

This project has a folder with two levels, each with its own index file. The server is the same one-mount setup from the earlier pages, with no extra options.

my-site/
  Cargo.toml
  src/main.rs
  assets/
    index.html
    style.css
    docs/
      index.html
      guide.html
Cargo.toml
[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"] }
assets/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Home</title>
</head>
<body>
  <h1>Home page</h1>
  <p>Read the <a href="/docs/">docs</a>.</p>
</body>
</html>
assets/docs/index.html
<h1>Docs Home</h1>
<p>This is the index file for the docs folder.</p>
assets/docs/guide.html
<h1>Guide</h1>
<p>This file lives in a subfolder.</p>
src/main.rs
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 and request the two directory URLs. Both return their folder's index file with a 200 status and content-type: text/html.

curl http://127.0.0.1:3000/
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Home</title>
</head>
<body>
  <h1>Home page</h1>
  <p>Read the <a href="/docs/">docs</a>.</p>
</body>
</html>
curl http://127.0.0.1:3000/docs/
<h1>Docs Home</h1>
<p>This is the index file for the docs folder.</p>

The root request served assets/index.html, and the /docs/ request served assets/docs/index.html. Neither URL named a file. The service supplied the filename itself, using the same rule at every level of the folder tree.

Working Setup:

If / returns the home page and /docs/ returns the docs home page, the index file behaviour is working. Both responses should carry content-type: text/html and a 200 OK status.

What append_index_html_on_directories Does

The method append_index_html_on_directories is a boolean switch on ServeDir. It takes true or false, and it defaults to true. The name describes the mechanism exactly: when the requested path is a directory, append index.html to it. The official tower-http 0.7.1 documentation puts it in one line: if the requested path is a directory, append index.html, and this is useful for static sites.

// The default - directory requests serve index.html
let service = ServeDir::new("assets");

// The same behaviour written out explicitly
let service = ServeDir::new("assets").append_index_html_on_directories(true);

// Directory requests no longer serve index.html
let service = ServeDir::new("assets").append_index_html_on_directories(false);

The method is a builder method, which means it takes the service, changes one setting, and returns the service. Builder methods chain, so it sits naturally alongside the other ServeDir options in the same expression. There is no separate configuration object and no global setting. Each ServeDir carries its own value, so two mounts can disagree: one folder can serve index files while another does not.

The name index.html is fixed. There is no method in tower-http 0.7.1 to choose a different filename, such as home.html or default.html. If the folder contains home.html but no index.html, a directory request does not fall back to it. It returns a 404, as the next section shows.

Turning the Index File Off

Turning the switch off changes directory requests from successes into 404s. Files are unaffected: a direct request for a file by its full name still works, because no directory lookup is involved.

src/main.rs
use axum::Router;
use tower_http::services::ServeDir;

#[tokio::main]
async fn main() {
    let app = Router::new().fallback_service(
        ServeDir::new("assets").append_index_html_on_directories(false),
    );

    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 this version and request the same four URLs. The pattern is the whole lesson.

curl -i http://127.0.0.1:3000/
HTTP/1.1 404 Not Found
content-length: 0
date: Sat, 14 Nov 2026 10:08:11 GMT
curl -i http://127.0.0.1:3000/docs/
HTTP/1.1 404 Not Found
content-length: 0
date: Sat, 14 Nov 2026 10:08:11 GMT
curl http://127.0.0.1:3000/index.html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Home</title>
</head>
<body>
  <h1>Home page</h1>
  <p>Read the <a href="/docs/">docs</a>.</p>
</body>
</html>
curl -i http://127.0.0.1:3000/docs
HTTP/1.1 404 Not Found
content-length: 0
date: Sat, 14 Nov 2026 10:08:11 GMT

With the switch off, / and /docs/ both return an empty 404, even though the index.html files are still on disk. The direct request for /index.html still returns the file, because that URL names a file, not a directory. The last request shows a second effect: /docs without a trailing slash also returns 404 now, instead of redirecting to /docs/. There is no point redirecting to a URL that would 404 anyway, so the redirect does not happen either. The switch controls the whole directory concept, not just the file lookup.

Turning It Off Breaks the Home Page:

The most common way beginners meet this method is by accident: they copy a ServeDir configuration from somewhere, it includes .append_index_html_on_directories(false), and suddenly the home page 404s while every file still works. If / 404s but /index.html works, this switch is the first thing to check.

The Index File and the Trailing Slash Redirect

Directory requests come in two spellings: with a trailing slash, /docs/, and without one, /docs. ServeDir handles them with two separate settings that work together. append_index_html_on_directories decides whether a directory serves index.html. redirect_to_trailing_slash decides whether a directory request without a slash is redirected to the slashed form. Both default to true, and the combination produces the behaviour seen on the earlier pages: /docs redirects to /docs/, and /docs/ serves assets/docs/index.html.

The redirect matters because of relative links. A page served at /docs that links to guide.html resolves that link to /guide.html, which is the wrong folder. The same page served at /docs/ resolves the link to /docs/guide.html, which is right. The redirect exists to keep relative links working, and it only triggers for paths that are directories on disk. A request for /style.css never redirects, because that path is a file.

The two settings can be combined in three useful ways. The defaults give the standard static site behaviour: redirect, then serve the index file. Turning the redirect off while keeping the index file on serves the index file directly at the bare path, with no redirect at all.

let service = ServeDir::new("assets").redirect_to_trailing_slash(false);

A request for /docs then returns the contents of assets/docs/index.html with a 200 status, and the URL in the browser stays /docs. That is convenient, but relative links inside the page resolve against /, not /docs/, so a link to guide.html breaks. Keep the redirect on unless you have a specific reason to turn it off, and that reason is usually that some other part of the system already handles the slash. The third combination, turning the index file off, was shown in the previous section: both the redirect and the file lookup disappear, and every directory URL becomes a 404.

Two Settings, One Directory:

append_index_html_on_directories answers the question "does a directory have a page?" redirect_to_trailing_slash answers the question "does the slashed URL or the bare URL name that page?" They are independent switches, and most applications leave both at their defaults.

When a Folder Has No Index File

A directory request only succeeds when the index.html file actually exists inside that directory. A folder with files but no index.html returns a 404 for the directory URL, while its files remain reachable by their direct paths. This is not an error in the configuration. It is the service refusing to invent a page for a folder that has none.

assets/
  index.html
  downloads/
    report.pdf
    data.csv

A request for /downloads/ returns 404, because there is no assets/downloads/index.html. Requests for /downloads/report.pdf and /downloads/data.csv return the files. This is the correct shape for a downloads folder: the files are public, but there is no landing page, and the server does not list the folder contents. ServeDir never produces a directory listing. If you want visitors to browse a folder, you write an index.html for it yourself, with links to the files, and the service will serve it like any other index file.

The same rule explains a common beginner confusion. A folder that contains only subfolders and no index.html 404s at its own URL, even though the subfolders each have index files. The service looks for exactly one file, index.html, in exactly the requested directory. It does not search deeper.

The Concept Behind the Index File

The index file convention is older than Axum, older than Rust, and older than most web frameworks. Early web servers needed an answer to a simple question: what should a URL that names a folder return? The convention they settled on was to look for a file named index.html in that folder and return it. The name stuck, and every static file server since has kept it, including ServeDir. A beginner who knows this convention can predict the behaviour of any static server, in any language, without reading its documentation.

The mental model is a book with a table of contents. The folder is the book, the files are the chapters, and index.html is the table of contents. Asking for the book gives you the table of contents. Asking for a chapter by name gives you the chapter. A book with no table of contents has no answer to "show me the book", even though every chapter is still there.

Why the Default Is On

The default is true because the common case for a static site is a folder of pages where each folder has a landing page. A documentation site has a home page at /, a section page at /docs/, and a section page at /blog/. Without the index file behaviour, every one of those URLs would need an explicit route or a redirect, and the folder structure would stop matching the URL structure. With it on, the folder structure is the site structure: add a folder with an index.html, and a new section appears at the matching URL.

The default also matches what browsers and users expect. A user who types a site address without a filename expects a page, not a 404. A search engine that follows a link to /docs/ expects a page. Turning the default off makes sense only when directory URLs must never resolve, such as a folder of raw assets that should only be reachable by exact filename.

A Richer Example - a Documentation Site with Sections

This example is a small documentation site with three sections. Each section is a folder with its own index.html landing page and one or more content pages. The server is the default configuration: no options at all.

assets/
  index.html
  style.css
  docs/
    index.html
    guide.html
    reference.html
  blog/
    index.html
    first-post.html
  downloads/
    report.pdf
assets/docs/index.html
<h1>Docs</h1>
<p>Start with the <a href="/docs/guide.html">guide</a>, then read the <a href="/docs/reference.html">reference</a>.</p>
assets/blog/index.html
<h1>Blog</h1>
<p>Read the <a href="/blog/first-post.html">first post</a>.</p>

The URL table for this site shows the rule applied at every level.

/                     -> assets/index.html            200
/docs/                -> assets/docs/index.html       200
/docs                 -> redirect to /docs/           307
/docs/guide.html      -> assets/docs/guide.html       200
/blog/                -> assets/blog/index.html       200
/blog/first-post.html -> assets/blog/first-post.html  200
/downloads/           -> 404, no index.html in folder
/downloads/report.pdf -> assets/downloads/report.pdf  200
/missing/             -> 404, no such folder

The /downloads/ row is the one to study. The folder exists, the files inside it are reachable, and the directory URL still 404s, because the rule is about the index.html file, not about the folder. The /missing/ row shows the same status for a folder that does not exist at all: the service does not distinguish between a missing folder and a folder without an index file. Both are just directory URLs with no index file to serve.

How a Directory Request Flows

The full path of a directory request through the service, from the browser to the disk and back, looks like this in plain text.

Browser asks for /docs/
        |
        v
ServeDir joins the folder path and the request path
  assets + /docs/ = assets/docs/
        |
        v
The path is a directory, not a file
        |
        v
append_index_html_on_directories is true, so index.html is appended
  assets/docs/ + index.html = assets/docs/index.html
        |
        v
The file exists, so it is opened and read
        |
        v
Content type is guessed from the .html extension: text/html
        |
        v
Response sent with 200 OK and the file bytes

A request for /docs without the slash takes a detour before this flow: the redirect setting sends the browser to /docs/, and the flow above runs on the second request. A request for a folder with no index.html leaves the flow at the open step and returns the empty 404.

Testing It

Index file behaviour is easy to test in memory, because the difference between the two settings is a status code. The tests below build the application twice, once with the default and once with the switch off, and check the root URL in each.

tests/index_file_test.rs
use axum::{body::Body, http::{Request, StatusCode}, Router};
use tower::ServiceExt;
use tower_http::services::ServeDir;

#[tokio::test]
async fn root_serves_index_by_default() {
    let app = Router::new().fallback_service(ServeDir::new("assets"));
    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
    assert_eq!(response.headers()["content-type"], "text/html");
}

#[tokio::test]
async fn root_is_404_when_index_is_disabled() {
    let app = Router::new().fallback_service(
        ServeDir::new("assets").append_index_html_on_directories(false),
    );
    let response = app
        .oneshot(
            Request::builder()
                .uri("/")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::NOT_FOUND);
}

#[tokio::test]
async fn direct_index_path_still_works_when_disabled() {
    let app = Router::new().fallback_service(
        ServeDir::new("assets").append_index_html_on_directories(false),
    );
    let response = app
        .oneshot(
            Request::builder()
                .uri("/index.html")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.status(), StatusCode::OK);
}

The third test pins down the exact scope of the switch: it changes directory URLs only. A direct file request is unaffected. The tower crate is needed as a dev dependency with the util feature, as on the earlier pages.

Cargo.toml
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }

Run the tests with cargo test. All three pass.

Common Beginner Mistakes

Naming the File home.html or Index.html

# Wrong - the service only looks for index.html, exactly this name
assets/
  Index.html
  home.html

A request for / returns 404, because the service looks for index.html and nothing else. The fix is to rename the file to index.html, all lowercase. On Linux, filenames are case-sensitive, so Index.html and index.html are two different files, and the service only recognises the lowercase one. On macOS and Windows, the filesystem may treat them as the same file, which hides the bug on a developer machine and reveals it on a Linux server. Always use the exact lowercase name.

The Bug That Only Appears on the Server:

A site that works on a developer's Mac and 404s on a Linux server is very often this mistake: the file is named Index.html or HOME.html, and the case-insensitive local filesystem hid it. Check the exact filename with ls on the server before changing any code.

Expecting a Directory Listing

Requesting /downloads/ does not produce a list of the files in downloads. ServeDir never lists directory contents. It serves the index.html inside the directory, or returns 404 when there is none. If you want a browsable folder, write the index.html yourself with links to the files.

Turning the Switch Off and Losing the Home Page

// Wrong for a normal site - the home page stops working
let service = ServeDir::new("assets").append_index_html_on_directories(false);

The home page 404s while every file still works, which looks like a broken mount but is only this switch. The fix is to remove the method call and let the default true apply. Only turn it off when directory URLs must never resolve.

Linking to the Folder Without the Slash

<a href="/docs">Docs</a>

This link works, because the server redirects /docs to /docs/, but it costs an extra round trip on every click, and it depends on the redirect setting being on. Link to /docs/ directly. The slash is part of the URL, and writing it saves the redirect.

Putting the Index File in the Wrong Folder

An index.html at assets/docs.html does not make /docs/ work. The file must be inside the folder it represents: assets/docs/index.html. When a section URL 404s but the section files load, check where the index file actually sits. The folder structure and the URL structure must match exactly.

Final Complete Example

Here is everything from this page put together: a documentation site with a home page, two sections with landing pages, a downloads folder with no landing page, and the default index file behaviour. The server is the plain one-mount version, because the defaults already do the right thing.

src/main.rs
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();
}
assets/
  index.html
  style.css
  docs/
    index.html
    guide.html
    reference.html
  blog/
    index.html
    first-post.html
  downloads/
    report.pdf
    data.csv
Cargo.toml
[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"] }

Check the behaviours in order: / serves the home page, /docs/ serves the docs landing page, /docs redirects to /docs/, /downloads/ returns 404 while /downloads/report.pdf returns the file, and /index.html returns the same page as /. Each behaviour is the same rule applied to a different folder.

Summary

The index file rule is the quiet convention that turns a folder tree into a website. A directory URL is answered by the index.html inside that directory, the filename is fixed and lowercase, a folder without one returns 404 instead of a listing, and the trailing slash redirect exists so relative links inside the served page resolve correctly. The switch append_index_html_on_directories controls the whole rule, and it defaults to on because the common case is a site made of landing pages.

The decision framework is one question: should a folder URL show a page? If yes, put an index.html in the folder and leave the default alone. If no, either leave the folder without an index.html, which 404s the directory URL while keeping the files reachable, or turn the switch off, which 404s every directory URL in that mount. Either way, the folder structure stays the site structure, and the server never needs a route per page.