Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 30 ยท Serving Content

Static Files, Caching and MIME Types

Serve static files fast with nginx and Apache: root and index, MIME types, ETag and Last-Modified, Cache-Control, immutable assets, pre-compression and error pages.

Serving files from disk is the oldest job of a web server, and it is where nginx and Apache are at their best. A well-configured server hands out a stylesheet in microseconds. A badly configured one makes every visitor download the same 300 KB bundle on every page view, or, worse, keeps serving a stale copy for a year after you fixed a bug.

In this lesson you will map URLs to files with root and index, learn how MIME types decide how a browser treats a file, understand conditional requests (ETag, Last-Modified, status 304), choose Cache-Control rules for fingerprinted and unfingerprinted files, serve pre-compressed files, and set up directory listings and custom error pages.

The real server configuration below sits in read-only blocks, because this site cannot run nginx or Apache. The interactive examples are small JavaScript stand-ins that model a browser cache and a server so you can watch the rules work. They are not the real servers.

Mapping URLs to files

Both servers append the URL path to a base directory. Nginx calls it root, Apache DocumentRoot.

NGINX
server {
    listen 80;
    server_name example.com;
    root /var/www/example/public;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
APACHE
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/example/public
    DirectoryIndex index.html

    <Directory "/var/www/example/public">
        Require all granted
        Options -Indexes
    </Directory>
</VirtualHost>

A request for /css/site.css becomes the file /var/www/example/public/css/site.css. A request for a directory such as /docs/ looks for the index file inside it (index in nginx, DirectoryIndex in Apache). The nginx try_files line says: try the URI as a file, then as a directory, and answer 404 if neither exists. Keep root at a dedicated public folder, never at the project root, so source code, .env files and backups are not reachable by URL.

Two performance directives matter for static files. In nginx, sendfile on; lets the kernel copy file data straight to the socket without passing it through the worker's memory, and tcp_nopush on; helps it fill packets. Apache has the equivalent EnableSendfile On. Both are normally already on in the packaged configs. One exception: on network file systems (NFS, some shared folders in virtual machines) sendfile can serve stale or corrupt data, and Apache's documentation recommends EnableSendfile Off there.

MIME types: what the file is

The server tells the browser what it is sending in the Content-Type header, and the browser trusts it. A .css file served as text/plain will not style anything; a .js file served as text/html may be refused as a module script. The mapping from file extension to type comes from a table:

NGINX
http {
    include       mime.types;
    default_type  application/octet-stream;
}
APACHE
TypesConfig conf/mime.types
AddType application/wasm .wasm

Unknown extensions fall back to application/octet-stream, which browsers download instead of displaying. When you add a new format (.wasm, .webmanifest, a font), add its type explicitly. Pair the types with X-Content-Type-Options: nosniff (covered in Hardening and Security Headers) so browsers do not guess a different type than the one you declared.

Conditional requests and 304

Every response for a file can carry two validators:

  • Last-Modified: the file's modification time.
  • ETag: an opaque fingerprint of the content version, such as "6641-5f2a". Nginx builds it from the modification time and size; Apache by default from modification time and size as well (it no longer includes the inode).

When the browser asks for the same URL again after its copy has gone stale, it sends the validator back in If-None-Match or If-Modified-Since. If the file is unchanged the server answers 304 Not Modified with no body, and the browser reuses its stored copy. You save the transfer, not the round trip. If both headers are present, the ETag wins.

A request has three outcomes

Fresh Still inside max-age. No request at all.
Revalidate Stale. Ask the server, with ETag.
Download Changed or unknown. Full 200 response.

The cheapest request is the one never sent.

1 / 2

The stand-in below plays a browser and a server with a fake clock. The server marks /app.css as fresh for 60 seconds. Read each line: cache means no network at all, 304 means a tiny revalidation, 200 means a full download.

JS Stand-in: a conditional-request (304) simulator

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice what the second visit proves: inside max-age the browser does not talk to the server at all. After it expires, the 304 costs only headers, and after the file changes the next revalidation finds the new ETag and downloads the file again. The weakness of this scheme is the first line of each period: until the clock runs out, the browser will not notice a change. That is the problem fingerprinting solves.

Cache-Control: telling browsers how long

The Cache-Control response header carries the rules:

Directive Meaning
max-age=N The copy is fresh for N seconds
no-cache Keep a copy but revalidate before every use (not "do not store")
no-store Do not keep it at all (private data)
public / private Shared caches (CDN) may or may not store it
immutable It will never change while fresh; do not even revalidate on reload
s-maxage=N Like max-age, for shared caches such as a CDN only

The best strategy combines two kinds of files:

  • Fingerprinted assets, whose names contain a hash of their content (app.3f9c1d2a.js). Their content never changes under that name, so give them the longest lifetime: max-age=31536000, immutable (one year). A new build produces new names, so nothing stale is ever served.
  • HTML pages and unfingerprinted files, whose names stay the same. Use no-cache (always revalidate with ETag, cheap 304s) or a short max-age.
NGINX
location ~* \.[0-9a-f]{8,}\.(js|css|woff2|png|webp|svg)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}

location ~* \.html$ {
    add_header Cache-Control "no-cache";
}

Nginx also has expires 1y;, which sets both Expires and Cache-Control: max-age. Beware an nginx rule that bites: add_header in a location replaces all add_header lines inherited from the outer level (see Nginx Configuration Syntax). In Apache you need mod_expires and mod_headers:

APACHE
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType image/webp "access plus 1 month"
    ExpiresByType text/css   "access plus 1 year"
</IfModule>

<FilesMatch "\.[0-9a-f]{8,}\.(js|css|woff2)$">
    Header set Cache-Control "public, max-age=31536000, immutable"
</FilesMatch>

The second stand-in chooses a policy per file and also shows the MIME lookup and the pre-compressed file decision.

JS Stand-in: policy, MIME type and .gz lookup per file

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Look at what happens with Accept-Encoding: the JavaScript file has a .gz twin on disk, so it is served from it when the client accepts gzip, but the PNG has none and goes out unchanged. Unknown extensions such as .xyz fall back to the download type.

Pre-compressed files

Compressing a text file on every request wastes CPU on content that never changes. Pre-compression does it once at build time: you keep app.js, app.js.gz and optionally app.js.br side by side, and the server picks one by the Accept-Encoding header. In nginx, gzip_static on; (part of the standard gzip static module, which most distribution packages include) serves .gz twins; Brotli needs the third-party ngx_brotli module for brotli_static on;. Apache has no one-line switch for this; you combine RewriteRule (to point to the .gz file), AddEncoding gzip .gz and a Vary: Accept-Encoding header, or you simply rely on dynamic mod_deflate. The trade-offs of gzip versus Brotli are in HTTP/2, HTTP/3, gzip and Brotli. Never compress images, video or archives again: they are already compressed.

Directory listings and error pages

If a directory has no index file, nginx's autoindex on; or Apache's Options +Indexes generates a listing of the files inside. That is useful for a download mirror and a leak everywhere else, so leave it off by default (see .htaccess, Directory Rules and AllowOverride).

Custom error pages replace the plain default:

NGINX
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;

location = /404.html {
    internal;
}
APACHE
ErrorDocument 404 /404.html
ErrorDocument 503 /maintenance.html

internal stops visitors from requesting /404.html directly as a normal page. Keep error pages self-contained (inline CSS, no database calls): they are served exactly when something else is broken.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A browser has a stale cached copy and sends If-None-Match with the stored ETag. The file has not changed. What does the server answer?

    A matching validator produces 304 with only headers. The browser reuses its stored body and treats the copy as fresh again.
  2. 2. Which Cache-Control value is right for a fingerprinted file like app.3f9c1d2a.js?

    The hash in the name changes whenever the content does, so the file can safely be cached for a year. A new build gets a new URL.
  3. 3. What does Cache-Control: no-cache really mean?

    no-cache is a revalidation rule, not a ban on storing. no-store is the one that forbids keeping a copy.
  4. 4. Why serve app.js.gz that was compressed at build time instead of compressing on each request?

    Pre-compression pays the cost once at build time, so the server just sends bytes, and you can afford the slowest, smallest setting.
  5. 5. A file with the unknown extension .xyz is requested. What Content-Type does the server send by default?

    Both servers fall back to the generic binary type, which browsers download instead of rendering.

Summary

  • root (nginx) and DocumentRoot (Apache) map URLs to files; keep them pointed at a dedicated public folder.
  • sendfile makes static delivery cheap; the types table decides the Content-Type, and unknown extensions become downloads.
  • ETag and Last-Modified enable conditional requests: a matching validator gets a body-less 304.
  • Give fingerprinted assets max-age=31536000, immutable; give HTML no-cache or a short lifetime.
  • Pre-compress text assets at build time and let gzip_static (or rewrite rules in Apache) serve them.
  • Leave directory listings off, and use self-contained custom error pages.

Next: PHP, FastCGI and Application Servers.