Learn Labs
Serving & Proxying

Static Files

try_files, caching headers for fingerprinted assets, gzip, and sendfile

Serving files is what Nginx was first built for, and still what it does best. With sendfile on, a worker asks the kernel to copy a file straight from the page cache to the socket, without the bytes passing through user space.

The site

root /usr/share/nginx/html;URI /assets/x.css -> /usr/share/nginx/html/assets/x.csslocation / {try_files $uri $uri/ /index.html;the file, a directory, else the app shell}

try_files checks each candidate in order and serves the first that exists. The final /index.html makes /about (no such file) return the single-page app, which then routes on the client. That's why /about returned 200 text/html in the lab.

Caching: fingerprint, then cache forever

Browsers and CDNs cache based on Cache-Control. The safe pattern:

  • HTML (index.html): short or no caching, so a deploy is visible at once.
  • Assets with a content hash in their name (app.3f9a2c.css): cache for a year, immutable. A changed file gets a new name, so a stale copy is never served.
location /assets/ {add_header Cache-Control "public, max-age=31536000, immutable";no "always"include /etc/nginx/snippets/security-headers.conf;access_log off;}
asset cache:       public, max-age=31536000, immutable
missing asset:     404 cache-control: None

Compression

gzip on;gzip_comp_level 5;1-9; above ~5 costs CPU for little gaingzip_min_length 1024;not worth it for tiny responsesgzip_proxied any;also compress proxied responsesgzip_vary on;Vary: Accept-Encoding, so caches keep both formsgzip_types text/plain text/css application/json application/javascript image/svg+xml;
catalog.json identity  -      84,241 bytes on the wire
catalog.json gzip      gzip    7,980 bytes on the wire

A 10.5× reduction for JSON. text/html is always compressed when gzip is on; images and video are already compressed and aren't listed. For the best ratios, precompress assets at build time (.gz and .br files) and serve them with gzip_static on; Brotli needs a third-party module in open-source Nginx.

Lab

  1. Request /about, /asets/app.css and /assets/nope.css. Which return 200 and which 404, and why?
  2. Compare curl -so /dev/null -w '%{size_download}' for catalog.json with and without -H 'Accept-Encoding: gzip'.
  3. Set gzip_comp_level 9, reload, and compare the size. Was it worth it?

On this page