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
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.
The same fallback hides broken links: a mistyped /asets/app.css also
returns index.html with status 200, and the browser tries to parse HTML
as CSS. Limit the fallback to the paths your app actually routes, and
let missing assets return 404 (this config's /assets/ location has no
fallback).
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.
asset cache: public, max-age=31536000, immutable
missing asset: 404 cache-control: NoneThe first version added that header with always, which applies it to
error responses too. A request for an asset that wasn't deployed yet
returned a 404 that browsers and CDNs were told to keep for a year. Then
the deploy finished, and users kept the 404. always belongs on security
headers, not on caching headers.
Compression
catalog.json identity - 84,241 bytes on the wire
catalog.json gzip gzip 7,980 bytes on the wireA 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
- Request
/about,/asets/app.cssand/assets/nope.css. Which return 200 and which 404, and why? - Compare
curl -so /dev/null -w '%{size_download}'forcatalog.jsonwith and without-H 'Accept-Encoding: gzip'. - Set
gzip_comp_level 9, reload, and compare the size. Was it worth it?