For a plain static site (a built blog, marketing page, or dist/ from a bundler), you just need root, index, and a try_files that returns a real 404 for missing files.
server {
listen 80;
server_name example.com;
root /var/www/example.com;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}
What each line does:
root /var/www/example.com;— the directory on disk. A request for/about/page.htmlserves/var/www/example.com/about/page.html.index index.html;— what to serve when a directory is requested (/→/index.html).try_files $uri $uri/ =404;— try the exact file, then the directory (with its index), and if neither exists return a real 404 instead of an ugly default or an infinite loop.
Common additions:
- Don’t serve dotfiles like
.gitor.env:
location ~ /\.(?!well-known) {
deny all;
}
autoindex off;is the default — keep directory listings off unless you specifically want a file index.- For pretty URLs without the
.html(e.g./about→about.html), use:
location / {
try_files $uri $uri.html $uri/ =404;
}
Add caching for assets (see the asset-cache recipe) and compression (the gzip recipe) on top of this.
sudo nginx -t && sudo nginx -s reload