Static File MIME Types - How Content-Type Is Guessed and Set

Learn what a MIME type is, how the browser uses the Content-Type header, how tower-http guesses it from the file extension with mime_guess, and how to set it explicitly

A MIME type is a short label that names the kind of data in a response body. It travels in the Content-Type header, and it is the browser's only reliable instruction for what to do with the bytes it just received. text/html means render a page. text/css means apply a stylesheet. text/javascript means run a script. image/png means show a picture. Without the label, the browser must guess, and the guess is often wrong. This page explains what the label is, how the browser uses it, how tower-http guesses it from the file extension with the mime_guess crate, what happens when the extension is unknown, and how to set the label yourself when the guess is wrong.

Where This Fits

The earlier pages showed ServeDir sending a content-type header with every file, and the values changed per extension without any configuration. That header was doing quiet work in every example: it is why the browser rendered the page instead of downloading it, applied the stylesheet instead of showing it as text, and ran the script instead of displaying it. This page opens up that mechanism. It is the last piece of the file-serving picture: the bytes are the file, the path is the mapping, and the MIME type is the label that makes the browser handle the bytes correctly.

Think of it like the label on a parcel. The parcel is the file. The address is the URL. The label says what is inside: glass, books, or electronics. The delivery driver does not open the parcel to check. They read the label and handle it accordingly. The browser is the driver, and the Content-Type header is the label.

What a MIME Type Is

A MIME type has two parts separated by a slash: a general family and a specific kind. The family is broad: text for readable text, image for pictures, audio for sound, video for moving pictures, font for typefaces, and application for everything else, including JSON data and compiled code. The specific kind narrows it down: text/html for a web page, text/css for a stylesheet, image/png for a PNG picture, application/json for JSON data. Some types carry a suffix after a plus sign, such as image/svg+xml, which means an SVG picture written in XML.

The name MIME comes from Multipurpose Internet Mail Extensions, an old email standard that needed a way to label attachments. The web adopted the same labels for HTTP, and they stuck. In HTTP, the label appears as the value of the Content-Type header on a response. The header is plain text, and the browser reads it before it reads the body.

HTTP/1.1 200 OK
content-type: text/html
content-length: 132

<!DOCTYPE html>
...

A MIME type describes the bytes, not the file. Two files with the same extension have the same type. Two files with different extensions have different types, even if their contents are identical. A file named notes.txt containing HTML markup is still text/plain to the browser, because the label comes from the extension, not from the contents.

How the Browser Uses the Content Type

The browser decides what to do with a response by reading the Content-Type header first and the body second. The table below shows the decisions for the file types a beginner meets most often. Each row is a rule the browser follows without asking the user.

Content-Type           Browser action
---------------------  ----------------------------------------
text/html              Render the body as a web page
text/css               Apply the body as a stylesheet
text/javascript        Run the body as a script
application/json       Treat the body as data, show as text
image/png              Show the body as a picture
image/svg+xml          Show the body as a vector picture
font/woff2             Load the body as a web font
application/wasm       Load the body as a WebAssembly module
video/mp4              Play the body as a video
application/octet-stream  Offer the body as a download

The consequences of a wrong label are concrete, not theoretical. A stylesheet served as text/html is not applied, and the page appears unstyled. A script served as text/plain is not run, and the page appears dead. A page served as application/octet-stream is offered as a download instead of rendered. Modern browsers are strict about scripts in particular: a JavaScript file served with the wrong type is blocked outright, with an error in the console saying the MIME type did not match. The browser does this deliberately, because running a file as code when the server labelled it as something else is a security risk.

The header also decides what happens when a user navigates directly to a file. A .json URL with application/json shows the data as text in the browser. The same URL with application/octet-stream triggers a download prompt. The bytes are identical in both cases. Only the label changed.

The Browser Trusts the Header, Not the File:

A file named app.js containing valid JavaScript will not run if the server labels it text/plain. A file named page.html containing valid HTML will not render if the server labels it application/octet-stream. When a page loads but its styling or scripts are missing, the Content-Type header is one of the first things to check, and curl -i shows it directly.

How tower-http Guesses the Type

ServeDir does not inspect file contents. It looks at the file extension, the part after the last dot in the filename, and asks a crate called mime_guess what type that extension means. The mime_guess crate holds a large table mapping extensions to MIME types, built from the same registry web servers have used for years. The guess happens in ServeDir's file-opening code: it calls mime_guess::from_path with the file path, takes the first guess, and falls back to application/octet-stream when the table has no entry.

The guessing is case-insensitive on the extension. A file named UPPER.HTML is served as text/html, exactly like lower.html, because the crate lowercases the extension before looking it up. That matters on Linux, where filenames are case-sensitive and a capitalised extension is easy to create by accident.

The table below shows the guesses ServeDir actually returned for the files in the scratch project used to verify this page. Every value was observed with curl -i against a live server, not copied from a reference.

Extension    Content-Type returned
---------    ---------------------
.html        text/html
.css         text/css
.js          text/javascript
.json        application/json
.png         image/png
.svg         image/svg+xml
.woff2       font/woff2
.wasm        application/wasm
.mp4         video/mp4
.tar.gz      application/gzip
.qwerty      application/octet-stream
.zzz         application/octet-stream

Two rows deserve attention. The .tar.gz file is guessed from its last extension only, .gz, so the type is application/gzip, not anything about tar archives. And .qwerty and .zzz are unknown extensions, so they fall back to application/octet-stream, the generic binary type. The fallback is the subject of the next section.

Using mime_guess Directly

The same guessing engine is available as a crate of its own, and it is the right tool whenever your own code needs to name a content type. The three functions below are the ones that matter. from_path guesses from a file path. from_ext guesses from a bare extension string, without a filename. Both return a MimeGuess value, which is a small list of candidate types, usually one, sometimes two, and empty when the extension is unknown.

use mime_guess::MimeGuess;

fn main() {
    let guess = mime_guess::from_path("photo.png");
    println!("first: {:?}", guess.first());
    println!("all: {:?}", guess.iter().collect::<Vec<_>>());
    println!("octet: {}", guess.first_or_octet_stream());

    let ext = mime_guess::from_ext("wasm");
    println!("wasm: {:?}", ext.first());
}

Running this program prints the guesses for each input. The output below is the real output from the verification run for this page.

photo.png   first=Some("image/png")   octet=image/png
wasm        first=Some("application/wasm")

The MimeGuess value offers four ways to turn the guess into a single type. first() returns an Option, which is Some when the table has an entry and None when it does not. first_or_octet_stream() returns the first guess, or application/octet-stream when there is none. first_or_text_plain() returns the first guess, or text/plain when there is none. first_or(default) returns the first guess, or any default type you supply. The first_or form is the flexible one: it lets you choose the fallback per situation instead of accepting the generic binary type.

use mime_guess::from_ext;

fn main() {
    let unknown = from_ext("qwerty");
    println!("first: {:?}", unknown.first());
    println!("octet: {}", unknown.first_or_octet_stream());
    println!("plain: {}", unknown.first_or_text_plain());
    println!("custom: {}", unknown.first_or(mime::TEXT_PLAIN));
}
first: None
octet: application/octet-stream
plain: text/plain
custom: text/plain

An unknown extension produces None from first(), and each fallback method supplies its own answer. Which fallback is right depends on the file. A binary file of unknown kind should stay application/octet-stream, so the browser offers a download. A text file with a made-up extension, such as notes in a .log file that the table does not know, reads better as text/plain, so the browser shows it. The choice is yours, and first_or is how you make it.

The crate also answers the reverse question: given a MIME type, which extensions map to it? get_mime_extensions_str returns the list, or None when the type is unknown.

fn main() {
    println!("{:?}", mime_guess::get_mime_extensions_str("text/html"));
    println!("{:?}", mime_guess::get_mime_extensions_str("application/x-bogus"));
}
Some(["htm", "html", "hxt", "shtml"])
None

The text/html type maps to four extensions, which is why .htm files are served as HTML just like .html files. The bogus type maps to nothing.

What Happens for Unknown Extensions

When the extension is not in the table, ServeDir sends application/octet-stream. That type means "arbitrary binary data", and it is the safe default: the browser does not try to render it, run it, or apply it. It offers the file as a download. Two files in the verification project proved this. A file named data.qwerty and a file named data.zzz, both containing the text weird, were served with content-type: application/octet-stream and a 200 status.

curl -i http://127.0.0.1:3000/data.qwerty
HTTP/1.1 200 OK
content-type: application/octet-stream
accept-ranges: bytes
last-modified: Sat, 14 Nov 2026 10:08:10 GMT
etag: "6af8330a.275f7d46-6"
content-length: 6
date: Sat, 14 Nov 2026 10:08:11 GMT

weird

A file with no extension at all behaves the same way. A file named README has no extension to look up, so the guess is empty and the fallback applies. The file still serves with a 200 status. Only the label is generic.

The fallback is safe, but it is not always what you want. A text file with a custom extension, such as a .log file or a data file in a format your application invented, is text the user should be able to read in the browser. Served as application/octet-stream, it downloads instead. That is the situation where an explicit type, covered in the next section, earns its place.

An Extension You Invented May Already Mean Something:

Before inventing a custom extension, check what it already maps to. A file named data.xyz is served as chemical/x-xyz, because .xyz is a real chemical file format in the mime_guess table. A made-up extension can collide with a real one, and the browser will then treat your text file as a chemical model. Use a distinctive extension, or set the type explicitly.

Setting the Type Explicitly

ServeDir has no per-extension override. There is no method to tell it that .qwerty means text/plain. When the guess is wrong or missing, the explicit type is set somewhere else: on the single file, or in your own serving code.

For one file, ServeFile offers a constructor that takes the type along with the path. ServeFile::new_with_mime accepts a &Mime value from the mime crate, and the file is served with exactly that type, whatever its extension says.

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

#[tokio::main]
async fn main() {
    let app = Router::new().route_service(
        "/notes",
        ServeFile::new_with_mime("assets/data.qwerty", &mime::TEXT_PLAIN),
    );

    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 mime crate is needed as a dependency for the mime::TEXT_PLAIN constant. route_service mounts the service at one exact path, so /notes serves the file and nothing else does.

Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }
mime = "0.3"
mime_guess = "2"

A request for /notes now returns the file as plain text, while the same file under ServeDir would have been application/octet-stream.

curl -i http://127.0.0.1:3000/notes
HTTP/1.1 200 OK
content-type: text/plain

For a whole folder, the explicit type belongs in your own serving code. The embedded service from the previous page is the natural place: it already guesses the type with mime_guess, so the override is one arm of the match, choosing a type for the custom extension before falling back to the guess.

let mime = if path.ends_with(".qwerty") {
    mime::TEXT_PLAIN
} else {
    mime_guess::from_path(path).first_or_octet_stream()
};

This snippet is the pattern, not a full program: check the custom extension first, guess everything else. The order matters. The explicit rule must run before the guess, or the guess wins and the file downloads again. The same pattern works in a handler that reads files from disk: read the file, pick the type with an explicit rule plus a guess, set the header, return the bytes.

The Fix Is One Header:

When a file downloads instead of displaying, or a stylesheet is ignored, the fix is almost always the Content-Type header. Check it with curl -i, find the wrong value, and set the right one explicitly. The bytes were fine all along.

How a Response Gets Its Content Type

The full path of a content type decision, from the request to the header, looks like this in plain text.

Browser asks for /style.css
        |
        v
ServeDir finds assets/style.css on disk
        |
        v
mime_guess looks up the .css extension in its table
        |
        v
The table says text/css
        |
        v
Response sent with content-type: text/css
        |
        v
Browser reads the header first, then applies the body as a stylesheet

For an unknown extension, the flow takes a different branch after the lookup: the table has no entry, the fallback application/octet-stream is chosen, and the browser offers a download. For an explicit type, the lookup never runs: the code supplies the type directly, and the header carries it unchanged.

Testing It

Content types are tested by asserting on the header, not just the status. The tests below build the usual mounted ServeDir and check the header for three file types plus the unknown-extension fallback. The assertions compare the header value as a string, which is the same value curl -i prints.

tests/mime_test.rs
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 css_is_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 js_is_text_javascript() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/app.js")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.headers()["content-type"], "text/javascript");
}

#[tokio::test]
async fn unknown_extension_is_octet_stream() {
    let response = app()
        .oneshot(
            Request::builder()
                .uri("/data.qwerty")
                .body(Body::empty())
                .unwrap(),
        )
        .await
        .unwrap();
    assert_eq!(response.headers()["content-type"], "application/octet-stream");
}

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. A test like this catches the two most common regressions: a renamed file whose extension changed, and a new file type the table does not know.

Common Beginner Mistakes

Judging a File by Its Contents

// Wrong assumption - the contents are HTML, but the type comes from the extension
// A file named notes.txt containing "<h1>Hi</h1>" is served as text/plain

mime_guess never opens the file. It reads the extension and looks it up. Contents play no part. A text file full of HTML is text/plain. A binary file named photo.html would be served as text/html, because the extension says so. If the type is wrong, rename the file or set the type explicitly. Do not expect the server to notice what the file contains.

Serving JavaScript as text/plain

A script tag pointing at a file served with text/plain fails in modern browsers, which block scripts whose MIME type is not a JavaScript type. The console error names the type mismatch. The file is usually fine. The extension is usually wrong, such as a .txt file holding JavaScript, or a server that guessed the type from a custom extension. Rename the file to .js, or set the type explicitly.

A Blocked Script Fails Silently on the Page:

When the browser blocks a script over a wrong MIME type, the page still loads. It simply has no JavaScript: buttons do nothing, dynamic content never appears, and the only clue is a console error. A page that renders but does nothing is very often this mistake, and the fix is the header, not the script.

Assuming the Browser Will Sniff the Type

Browsers used to guess a file's type from its contents when the header was missing or generic. Modern browsers do this far less, and for scripts and stylesheets they refuse outright. A missing or generic content type is not a minor omission. It is the difference between a working page and a broken one. Always send the right header.

Setting the Type on the Wrong Response

An explicit type set on a ServeFile applies to that file only. It does not change the type of the same file served through a ServeDir mount elsewhere in the application. Each mount guesses independently. If the same file appears under two mounts, fix the type in both places, or rename the file so the guess is right everywhere at once.

Forgetting That .tar.gz Means the Last Extension

A file named archive.tar.gz is served as application/gzip, because only the last extension is looked up. A browser that receives it offers a gzip download, not a tar archive. That is correct behaviour for the name: the file is a gzip stream that happens to contain a tar archive. Name the file for what the browser should do with it, or set the type explicitly.

Final Complete Example

Here is everything from this page put together: a small server that serves a folder with guessed types, serves one custom-extension file with an explicit type, and includes the tests that pin the headers down. The folder holds one file of each kind, including the custom extension that proves the override.

src/main.rs
use axum::Router;
use tower_http::services::{ServeDir, ServeFile};

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route_service(
            "/notes",
            ServeFile::new_with_mime("assets/data.qwerty", &mime::TEXT_PLAIN),
        )
        .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
  app.js
  logo.png
  data.json
  data.qwerty
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"] }
mime = "0.3"
mime_guess = "2"

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

Check the three behaviours in order: /style.css returns text/css, /data.qwerty through the folder returns application/octet-stream, and /notes returns the same file as text/plain. The bytes never changed. Only the label did, and the label is what the browser acts on.

Summary

The content type is the smallest header with the largest consequences. It is a two-part label, guessed from the file extension by mime_guess, sent as the Content-Type header, and read by the browser before the body. A right label makes the browser render, apply, run, or show the file. A wrong label makes it ignore, block, or download the same bytes. An unknown extension falls back to application/octet-stream, which is safe but often not what a text file deserves.

The decision framework is one lookup and one question. First, let the guess run: for standard extensions it is right, and no code is needed. Then ask whether the guess matches what the file actually is. When it does not, or when the extension is unknown, set the type explicitly with ServeFile::new_with_mime for one file, or with an explicit rule before the guess in your own serving code. The bytes are the file. The label is the instruction. Get the instruction right, and the browser does the rest.