nginx Basics
nginx is fast, stable, and does exactly what you told it to. That last part is the problem. It never does what you meant.
The two commands that matter
Section titled “The two commands that matter”sudo nginx -t # test the config. ALWAYS before reload.sudo systemctl reload nginx # apply it without dropping connectionsMake nginx -t && systemctl reload nginx one motion, like a reflex. A broken config + restart = nginx doesn’t come back = every site on the box is down. reload with a broken config just fails, and the old config keeps running.
sudo nginx -T | less # dump the FULL effective config, all includes mergedWhen you don’t know where a directive is coming from, nginx -T and search. It’s always in some include you forgot existed.
Where config lives
Section titled “Where config lives”Debian/Ubuntu:
/etc/nginx/nginx.conf # main file. Rarely touch it./etc/nginx/sites-available/ # one file per site/etc/nginx/sites-enabled/ # symlinks to the ones that are on/etc/nginx/conf.d/*.conf # also included. Some people use this instead./var/log/nginx/access.log/var/log/nginx/error.log # read this. It usually tells you exactly what's wrong.Enable a site:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/sudo nginx -t && sudo systemctl reload nginxRHEL-family and the official nginx packages only use conf.d/. Same idea, fewer symlinks.
A basic static site
Section titled “A basic static site”/etc/nginx/sites-available/example.com:
server { listen 80; listen [::]:80; server_name example.com www.example.com;
root /var/www/example.com; index index.html;
location / { try_files $uri $uri/ =404; }
access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log;}sudo mkdir -p /var/www/example.comsudo chown -R $USER:www-data /var/www/example.comecho '<h1>it works, somehow</h1>' > /var/www/example.com/index.htmlnginx (as www-data) needs read on the files and execute (x) on every directory up the path. Serving out of /home/you/site fails because /home/you is usually 750. Put sites under /var/www and you’ll avoid this argument with yourself.
Pretty URLs (no .html at the end)
Section titled “Pretty URLs (no .html at the end)”You have about.html and blog/first-post.html, and you want people to see /about and /blog/first-post. Nobody wants .html in a link in this century.
server { listen 80; server_name example.com;
root /var/www/example.com; index index.html;
# 1. Anyone asking for /something.html gets bounced to /something if ($request_uri ~ ^/(.*)\.html(\?|$)) { return 301 /$1$is_args$args; }
# 2. /index -> / (so the redirect above doesn't leave you with /index) location = /index { return 301 /; }
location / { # 3. Try the exact file, then file + .html, then a directory index, then 404 try_files $uri $uri.html $uri/ =404; }
error_page 404 /404.html;}How it works:
try_files $uri $uri.html $uri/ =404is the actual trick. A request for/aboutchecks for a file calledabout(nope), thenabout.html(yes) and serves it. The URL in the browser stays/about.- The
ifblock redirects old.htmllinks to the clean version, so search engines don’t index two copies of every page. It matches against$request_uri(what the client actually sent), not$uri(which nginx rewrites internally). Matching$urithere gets you a redirect loop, because aftertry_filesfindsabout.html,$uribecomes/about.html. $uri/handles directories:/blog/serves/blog/index.html.
Trailing slashes
Section titled “Trailing slashes”Pick one style and stick with it. With the config above:
| Request | Result |
|---|---|
/about |
serves about.html |
/about.html |
301 → /about |
/blog/ |
serves blog/index.html |
/blog |
if blog.html exists, serves it. Otherwise nginx 301s to /blog/ |
If you have both blog.html and a blog/ directory, you made your own bed. blog.html wins, because it comes first in try_files.
Also strip .html from your internal links: <a href="/about">, not <a href="about.html">. The redirect works, but every click costs a round trip, and it looks sloppy.
Location matching (the part everyone guesses at)
Section titled “Location matching (the part everyone guesses at)”nginx picks one location per request. Not the first match, not all of them. It follows this order:
location = /exact— exact match. If it hits, done.- Longest prefix match is remembered. If that prefix uses
^~, it wins immediately, and regexes are skipped. - Regex locations (
~case-sensitive,~*insensitive) are checked in the order they appear in the file. First match wins. - If no regex matched, the remembered longest prefix wins.
location = /health { return 200 "ok\n"; } # exactlocation ^~ /static/ { root /var/www/assets; } # prefix, beats regexeslocation ~* \.(jpg|png|css|js)$ { expires 30d; } # regexlocation / { try_files $uri $uri/ =404; } # catch-all prefixWhen a location “isn’t working,” it’s because a different one matched. Add add_header X-Debug-Location "static" always; to each one temporarily and check with curl -I. Crude. Works.
root vs alias
Section titled “root vs alias”location /images/ { root /var/www/site; # /images/cat.png -> /var/www/site/images/cat.png}
location /images/ { alias /srv/pictures/; # /images/cat.png -> /srv/pictures/cat.png}root appends the full URI. alias replaces the location prefix. With alias, match your trailing slashes (/images/ ↔ /srv/pictures/). Mismatched slashes are a classic path traversal bug, and also a classic “why is everything 404.”
Things you’ll want eventually
Section titled “Things you’ll want eventually”server_tokens off; # don't advertise your version (in http {} block)client_max_body_size 50m; # default is 1m. "413 Request Entity Too Large" = this.
gzip on;gzip_types text/css application/javascript application/json image/svg+xml;
location ~* \.(css|js|png|jpg|svg|woff2)$ { expires 30d; add_header Cache-Control "public";}Reverse Proxy & TLS, for putting nginx in front of your apps and containers.