Skip to main content

Web servers and networking · Intermediate · 14 min

Serve static files fast with Nginx compression and cache headers

By Padding · Updated 18 Nov 2026
Ubuntu 26.04.1 LTS · Nginx 1.30.8 (nginx.org packages)

You will have Nginx 1.30 sending gzip-compressed text, precompressed build files and the right cache headers for fingerprinted assets and HTML, all checked with curl.

On this page

Two settings decide most of how fast a static site feels: how many bytes cross the network, and how often the browser has to ask for them again. Nginx handles both without any extra software. In this tutorial you build a tiny site with fingerprinted CSS and JavaScript, then turn on gzip, serve files you compressed ahead of time, tell browsers to keep assets for a year while always rechecking the HTML, and confirm every change with curl.

Fewer bytes matter most to people paying for every megabyte. Across much of Africa, many visitors browse on low-end Android phones with prepaid data bundles, so a stylesheet that shrinks from 3 KB to 1 KB, and is not downloaded again on the next visit, saves them real money.

The paths here belong to the Nginx package from nginx.org, which reads every *.conf file in /etc/nginx/conf.d/ inside its http block. If you have not installed it yet, follow /tutorials/install-nginx-on-ubuntu-26-04 first. The demo site listens on port 8080 so it sits beside anything you already serve on port 80.

Step 1 · Build a small site with fingerprinted assets

A fingerprinted file has a short hash of its contents in its name, such as app.3f9c2a1b.css. When the contents change, the name changes, so a browser can keep the old file forever without ever showing stale styles. Build tools such as Vite and webpack do this for you. Here a few shell commands do the same job, so you can see what the build produces.

Work in a throwaway folder in your home directory:

Bash
mkdir -p ~/fast-demo/src
cd ~/fast-demo/src
cat > app.css <<'CSS'
:root { --ink: #0b0c0e; --muted: #6a707b; --line: #d9dce1; --paper: #f1f2f4; }
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, sans-serif; color: var(--ink); background: var(--paper); line-height: 1.5; }
header { padding: 1.5rem 1rem; border-bottom: 1px solid var(--line); background: #ffffff; }
header h1 { margin: 0; font-size: 1.5rem; }
main { max-width: 40rem; margin: 0 auto; padding: 1.5rem 1rem; }
main p { margin: 0 0 1rem; color: var(--ink); }
main p.note { color: var(--muted); font-size: 0.9rem; }
.card { padding: 1rem; margin: 0 0 1rem; border: 1px solid var(--line); border-radius: 0.5rem; background: #ffffff; }
.card h2 { margin: 0 0 0.5rem; font-size: 1.1rem; }
.card p { margin: 0; color: var(--muted); }
.button { display: inline-block; padding: 0.5rem 1rem; border: 1px solid var(--ink); border-radius: 0.25rem; color: var(--ink); text-decoration: none; }
.button:hover, .button:focus { background: var(--ink); color: #ffffff; }
footer { padding: 1.5rem 1rem; border-top: 1px solid var(--line); color: var(--muted); font-size: 0.85rem; text-align: center; }
@media (min-width: 40rem) { header h1 { font-size: 2rem; } main { padding: 2rem 1rem; } .card { padding: 1.25rem; } }
@media (prefers-reduced-motion: no-preference) { .button { transition: background 120ms ease, color 120ms ease; } }
CSS
cat > app.js <<'JS'
// Show when the page was loaded and count clicks on the cards.
document.addEventListener('DOMContentLoaded', function () {
  var footer = document.querySelector('footer');
  var loaded = new Date();
  if (footer) {
    footer.textContent = 'Page loaded at ' + loaded.toLocaleTimeString() + '.';
  }
  var cards = document.querySelectorAll('.card');
  cards.forEach(function (card) {
    var count = 0;
    card.addEventListener('click', function () {
      count += 1;
      card.setAttribute('data-clicks', String(count));
      var label = card.querySelector('p');
      if (label) {
        label.textContent = 'Clicked ' + count + (count === 1 ? ' time.' : ' times.');
      }
    });
  });
});
JS

Now give each file a name with the first eight characters of its SHA-256 hash, and write an index.html that points at those names:

Bash
cd ~/fast-demo/src
css="app.$(sha256sum app.css | cut -c1-8).css"
js="app.$(sha256sum app.js | cut -c1-8).js"
mkdir -p ../build/assets
cp app.css "../build/assets/$css"
cp app.js "../build/assets/$js"
cat > ../build/favicon.svg <<'SVG'
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#0b0c0e"/><text x="16" y="22" font-size="16" text-anchor="middle" fill="#ffffff" font-family="system-ui, sans-serif">F</text></svg>
SVG
cat > ../build/index.html <<HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Fast demo</title>
<link rel="icon" href="/favicon.svg">
<link rel="stylesheet" href="/assets/$css">
<script src="/assets/$js" defer></script>
</head>
<body>
<header><h1>Fast demo</h1></header>
<main>
<div class="card"><h2>Compressed</h2><p>Text files travel as gzip.</p></div>
<div class="card"><h2>Cached</h2><p>Assets stay in the browser for a year.</p></div>
</main>
<footer></footer>
</body>
</html>
HTML

Copy the build into a folder Nginx can read:

Bash
sudo mkdir -p /var/www/fast-demo
sudo rm -rf /var/www/fast-demo/html
sudo cp -r ~/fast-demo/build /var/www/fast-demo/html

Check it worked

Bash
ls -l /var/www/fast-demo/html /var/www/fast-demo/html/assets
grep assets/ /var/www/fast-demo/html/index.html

You see index.html, favicon.svg and an assets folder holding one app.<hash>.css and one app.<hash>.js. The two grep lines in index.html name exactly those files.

Step 2 · Serve the site and record a baseline

Write a server block for the site. It has no compression or cache settings yet, so you can see what changes later:

Bash
sudo tee /etc/nginx/conf.d/fast-demo.conf > /dev/null <<'CONF'
server {
    listen 8080;
    listen [::]:8080;
    server_name _;

    root /var/www/fast-demo/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}
CONF
sudo nginx -t

nginx -t ends with syntax is ok and test is successful. Load the new configuration:

Bash
sudo systemctl reload nginx

Every check in this tutorial asks for the stylesheet by name, so keep its name in a variable. Set it again if you open a new terminal:

Bash
CSS=$(basename /var/www/fast-demo/html/assets/app.*.css)
echo "$CSS"
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' "http://127.0.0.1:8080/assets/$CSS"

Check it worked

The response starts with HTTP/1.1 200 OK and includes Content-Type: text/css, a Content-Length of about 1,300 bytes, plus Last-Modified and ETag lines. There is no Content-Encoding line: even though curl said it accepts gzip, Nginx sent the file as it is on disk.

Step 3 · Compress text responses with gzip

gzip works well on text: HTML, CSS, JavaScript, JSON, SVG. It does nothing useful for JPEG, PNG, WebP, video or fonts in WOFF2, which are already compressed, and compressing them again only costs CPU. Put the settings in their own file so they apply to every site on the server:

Bash
sudo tee /etc/nginx/conf.d/compression.conf > /dev/null <<'CONF'
gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_vary on;
gzip_proxied any;
gzip_types
    text/css
    text/plain
    text/xml
    text/javascript
    application/javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    image/svg+xml;
CONF
sudo nginx -t

What each line does:

  • gzip on turns the filter on. The packaged /etc/nginx/nginx.conf has it commented out, so this is the only gzip line in the http block.
  • gzip_comp_level 5 is a middle setting. Levels run from 1 to 9; above 5 or 6 the files get only slightly smaller while CPU use keeps rising.
  • gzip_min_length 256 skips tiny responses, where the gzip header and the extra work outweigh the saving. The value is compared with the response's Content-Length.
  • gzip_vary on adds Vary: Accept-Encoding, so a shared cache or CDN keeps compressed and plain copies apart.
  • gzip_proxied any also compresses responses when the request came through a proxy or CDN, which Nginx detects from the Via request header. The default, off, sends those requests uncompressed, including static files.
  • gzip_types lists the MIME types to compress. text/html is always included, and listing it again only produces a warning. Nginx 1.30's mime.types maps .js to application/javascript; text/javascript is listed too in case you or another tool change that mapping.

Reload Nginx:

Bash
sudo systemctl reload nginx

Check it worked

Ask for the stylesheet twice, once without and once with Accept-Encoding: gzip. Without --compressed, curl does not unpack the body, so size_download is the number of bytes that crossed the network:

Bash
CSS=$(basename /var/www/fast-demo/html/assets/app.*.css)
curl -s -o /dev/null -w 'plain: %{size_download} bytes\n' "http://127.0.0.1:8080/assets/$CSS"
curl -s -o /dev/null -w 'gzip:  %{size_download} bytes\n' -H 'Accept-Encoding: gzip' "http://127.0.0.1:8080/assets/$CSS"
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' "http://127.0.0.1:8080/assets/$CSS"

The gzip figure is well under half the plain one. The headers now include Content-Encoding: gzip and Vary: Accept-Encoding. There is no Content-Length (the body is sent in chunks as it is compressed), and the ETag starts with W/, which marks it as weak: the bytes differ from the file on disk, so Nginx can no longer promise a byte-for-byte match.

Step 4 · Serve files you compressed at build time

On-the-fly gzip repeats the same work for every request. For files that only change when you deploy, compress them once at the highest level and let Nginx send the result. The gzip_static module, which the nginx.org package includes, looks for <file>.gz next to the requested file and sends it to any client that accepts gzip.

Confirm the module is built in:

Bash
nginx -V 2>&1 | grep -o with-http_gzip_static_module

It prints with-http_gzip_static_module. Add gzip_static on; to the compression file. This rewrites the whole file with the new line at the top:

Bash
sudo tee /etc/nginx/conf.d/compression.conf > /dev/null <<'CONF'
gzip_static on;

gzip on;
gzip_comp_level 5;
gzip_min_length 256;
gzip_vary on;
gzip_proxied any;
gzip_types
    text/css
    text/plain
    text/xml
    text/javascript
    application/javascript
    application/json
    application/xml
    application/rss+xml
    application/atom+xml
    image/svg+xml;
CONF
sudo nginx -t

Keep gzip on as well, as a fallback for any text file without a .gz partner. Now make the .gz files as part of the build. -k keeps the original, which Nginx still needs for clients that do not accept gzip, and -9 is the slowest, smallest setting, which is fine when it runs once per deploy:

Bash
cd ~/fast-demo/build
find . -type f \( -name '*.css' -o -name '*.js' -o -name '*.svg' -o -name '*.html' \) -exec gzip -k -9 -f {} \;
find . -type f | sort

Copy the new build into place and reload Nginx:

Bash
sudo rm -rf /var/www/fast-demo/html
sudo cp -rp ~/fast-demo/build /var/www/fast-demo/html

cp -p keeps the modification times, so each .gz file stays at least as new as its original. Nginx does not check this, but it is how you can tell later that a .gz file was not left behind by an older build.

Bash
sudo systemctl reload nginx

Check it worked

Bash
CSS=$(basename /var/www/fast-demo/html/assets/app.*.css)
curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' "http://127.0.0.1:8080/assets/$CSS"
stat -c '%s bytes on disk' "/var/www/fast-demo/html/assets/$CSS.gz"

The response has Content-Encoding: gzip and, unlike the previous step, a Content-Length that equals the size of the .gz file on disk. The ETag no longer starts with W/. Those two details tell you Nginx sent the precompressed file instead of compressing on the fly.

Step 5 · Cache fingerprinted assets for a year and recheck HTML

Two kinds of file need opposite rules:

  • Fingerprinted assets never change under the same name. Tell browsers to keep them for a year and not to ask again: Cache-Control: public, max-age=31536000, immutable. The immutable token stops supporting browsers from revalidating even when the visitor presses reload.
  • HTML must always be fresh, because it is what points at the new fingerprinted names after a deploy. Cache-Control: no-cache does not mean "do not store". It means "store, but check with the server before each use". That check is cheap, as the next step shows.

A file with a fixed name that changes rarely, such as the favicon, can sit in between. The expires directive sets both an Expires date and a matching Cache-Control: max-age for it.

Rewrite the server block with three locations:

Bash
sudo tee /etc/nginx/conf.d/fast-demo.conf > /dev/null <<'CONF'
server {
    listen 8080;
    listen [::]:8080;
    server_name _;

    root /var/www/fast-demo/html;
    index index.html;

    # HTML and anything without a fingerprint: store, but revalidate each time.
    location / {
        try_files $uri $uri/ =404;
        add_header Cache-Control "no-cache";
    }

    # Files named like app.3f9c2a1b.css: the name changes when the content does.
    location ~* "\.[0-9a-f]{8}\.(css|js)$" {
        try_files $uri =404;
        add_header Cache-Control "public, max-age=31536000, immutable";
    }

    # A fixed name that changes rarely: keep it for a week.
    location = /favicon.svg {
        expires 7d;
    }
}
CONF
sudo nginx -t

Two details to watch:

  • The regular expression is in quotes because it contains { and }, which Nginx would otherwise read as the start of a block.
  • add_header in a location replaces every add_header from the server block rather than adding to it. If you set security headers at the server level, repeat them in each location that has its own add_header.

The fingerprinted location does not use expires on purpose. expires writes its own Cache-Control: max-age line, and combining it with an add_header Cache-Control would send two Cache-Control headers.

Bash
sudo systemctl reload nginx

Check it worked

Bash
CSS=$(basename /var/www/fast-demo/html/assets/app.*.css)
curl -s -D - -o /dev/null "http://127.0.0.1:8080/assets/$CSS" | grep -i '^cache-control'
curl -s -D - -o /dev/null http://127.0.0.1:8080/ | grep -i '^cache-control'
curl -s -D - -o /dev/null http://127.0.0.1:8080/favicon.svg | grep -iE '^(cache-control|expires)'

You see three answers: public, max-age=31536000, immutable for the stylesheet, no-cache for the home page, and max-age=604800 with an Expires date seven days ahead for the favicon. In a browser's developer tools, a second visit to the page shows the CSS and JavaScript loaded from the memory or disk cache with no network request.

Step 6 · See revalidation answer with 304 Not Modified

Because the HTML says no-cache, the browser asks before reusing its copy. It sends back what it was told last time: the ETag in an If-None-Match header, and the Last-Modified date in If-Modified-Since. If nothing has changed, Nginx answers 304 Not Modified with no body, a few hundred bytes instead of the whole page. Nginx sends both validators for static files by default (etag on), so there is nothing to configure.

Copy the home page's validators into variables, then send them back:

Bash
etag=$(curl -s -D - -o /dev/null http://127.0.0.1:8080/ | awk 'tolower($1)=="etag:" {print $2}' | tr -d '\r')
lastmod=$(curl -s -D - -o /dev/null http://127.0.0.1:8080/ | awk -F': ' 'tolower($1)=="last-modified" {print $2}' | tr -d '\r')
echo "ETag: $etag"
echo "Last-Modified: $lastmod"
curl -s -o /dev/null -w 'If-None-Match:     %{http_code}, %{size_download} bytes\n' -H "If-None-Match: $etag" http://127.0.0.1:8080/
curl -s -o /dev/null -w 'If-Modified-Since: %{http_code}, %{size_download} bytes\n' -H "If-Modified-Since: $lastmod" http://127.0.0.1:8080/

Check it worked

Both lines report 304, 0 bytes. Now prove the check notices a change. Update the page on the server and ask again with the old ETag:

Bash
echo '<!-- deployed again -->' | sudo tee -a /var/www/fast-demo/html/index.html > /dev/null
curl -s -o /dev/null -w '%{http_code}, %{size_download} bytes\n' -H "If-None-Match: $etag" http://127.0.0.1:8080/

This time the answer is 200 with the full page, because the file's size and modification time, which make up the ETag, have changed. A browser sending a weak ETag from a gzip response gets the same treatment: Nginx compares weak tags too.

Notice the trap this edit created: index.html.gz still holds the old page, and gzip_static sends it to every browser that accepts gzip, which is nearly all of them. Never edit files in place on a site that uses gzip_static. Change the source, rerun the build including the gzip -k -9 line, and copy the whole build into place.

Step 7 · Cut file system work with sendfile and open_file_cache

Three more settings reduce the work behind each request for a file:

  • sendfile on lets the kernel copy a file straight to the network socket, without passing it through Nginx's memory. The packaged nginx.conf already turns it on.
  • tcp_nopush on, used with sendfile, sends the response headers and the start of the file in full packets instead of a small packet for the headers alone.
  • open_file_cache keeps open file handles, sizes and modification times for files Nginx served recently, so it skips repeated open() and stat() calls on busy sites.

Check what the main configuration already sets:

Bash
grep -nE 'sendfile|tcp_nopush|gzip' /etc/nginx/nginx.conf

You see sendfile on; and commented-out lines for tcp_nopush and gzip. Adding sendfile again at the same level would fail with "sendfile" directive is duplicate, so the new file sets only the other two:

Bash
sudo tee /etc/nginx/conf.d/file-io.conf > /dev/null <<'CONF'
tcp_nopush on;

open_file_cache max=1000 inactive=30s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
CONF
sudo nginx -t

max=1000 caps how many files are remembered, and inactive=30s forgets files nobody asked for in that time. open_file_cache_valid 30s is how long Nginx trusts what it remembered before checking the file again. That means an index.html replaced in place can take up to 30 seconds to show. Fingerprinted assets are not affected, since a deploy gives them new names. If you need the new HTML at once, reload Nginx as the last step of each deploy. open_file_cache_errors on also remembers missing files, which helps when bots hammer the same 404s.

Bash
sudo systemctl reload nginx

Check it worked

Bash
sudo nginx -T 2>/dev/null | grep -E '^\s*(sendfile|tcp_nopush|open_file_cache)'
curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:8080/

The full configuration lists sendfile on, tcp_nopush on and the four open_file_cache lines, and the site still answers 200.

Step 8 · Decide whether you need Brotli or zstd

Brotli, and more recently zstd, compress text smaller than gzip, and current browsers accept both. Nginx itself has no built-in support for either, and the nginx.org repository does not package a module for them: its modules are acme, geoip, image-filter, njs, otel, perl and xslt. Your options are:

  • Build the third-party modules (google/ngx_brotli or tokers/zstd-nginx-module) yourself as dynamic modules. They must match your exact Nginx version, so every Nginx upgrade means a rebuild, and they get no security updates from apt.
  • Switch to Ubuntu's own nginx package, which is older (1.28 in the 26.04 archive) and has Brotli module packages built for it, libnginx-mod-http-brotli-filter and libnginx-mod-http-brotli-static. That package uses a different file layout from this tutorial.
  • Put a CDN in front of the server. Most CDNs compress with Brotli at the edge and cache your assets close to visitors, which helps more than the compression format does.

For most small sites, gzip at level 9 at build time plus long caching gets most of the benefit with nothing extra to maintain.

Check it worked

See what your Nginx can do today:

Bash
nginx -V 2>&1 | tr ' ' '\n' | grep -iE 'brotli|zstd' || echo "No Brotli or zstd module in this Nginx build"

On the nginx.org package it prints No Brotli or zstd module in this Nginx build, so gzip is the format to tune.

Step 9 · Remove the demo

When you are done, remove the demo site. The next command deletes /var/www/fast-demo, ~/fast-demo and the demo's server block, so check those names are not ones you use for anything else:

Bash
sudo rm -f /etc/nginx/conf.d/fast-demo.conf
sudo rm -rf /var/www/fast-demo ~/fast-demo
sudo nginx -t

Keep compression.conf and file-io.conf if you want those settings for your other sites, or remove them too, then reload:

Bash
sudo systemctl reload nginx

Check it worked

Bash
curl -sS -o /dev/null http://127.0.0.1:8080/ || echo "Nothing is listening on port 8080 any more"

curl reports that it could not connect, followed by Nothing is listening on port 8080 any more. Your other sites keep working, with compression and the file settings still applied if you kept those two files.

Next steps

  • Apply the same caching ideas to an API instead of files: /tutorials/set-caching-headers-for-api-responses.
  • Cache an application's responses in Nginx itself: /tutorials/cache-upstream-responses-with-nginx-proxy-cache.
  • Run this site beside others on port 80 with its own server name: /tutorials/host-multiple-sites-with-nginx-server-blocks.

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.