Sub topic 8
Serving static files
This chapter covers how Nginx maps a request to a file on disk and what it does when the file is missing. It assumes you can already install Nginx, edit files under /etc/nginx with sudo, and test and reload the configuration with nginx -t. It also assumes you know what a server block and a location block are.
How Nginx finds a file
A static file is a file that Nginx sends as it is, without running application code. Examples are HTML pages, CSS, JavaScript, images, and downloads.
Nginx builds the file path from two parts:
- The
rootdirective gives a base directory. - The request URI (the path in the request line, without the query string) is added to the end of that base.
With root /var/www/example.com/html;, a request for /css/site.css is read from /var/www/example.com/html/css/site.css. A request for / is a directory request. Nginx then tries the file names in the index directive, in order, inside that directory.
Here is the server block from the plan, which serves two host names:
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example.com/html;
index index.html;
location / {
try_files $uri $uri/ =404;
}
}$uri is a built-in variable that holds the normalized request path. try_files checks each argument in order and uses the first one that exists. The last argument is different. It is a fallback: a bare =404 returns that status code, and a path makes Nginx do an internal redirect to it.
For /about.html, the sequence is:
$uriis/about.html. If the file exists, Nginx serves it.- If not,
$uri/checks for a directory with that name and appliesindexinside it. - If neither exists, Nginx returns 404.
root versus alias
root appends the whole URI to the path. alias replaces the part of the URI that matched the location. The two behave differently, and mixing them up is a common source of 404 errors.
# root: /downloads/a.zip is read from /srv/files/downloads/a.zip
location /downloads/ {
root /srv/files;
}
# alias: /downloads/a.zip is read from /srv/archive/a.zip
location /downloads/ {
alias /srv/archive/;
}Follow these rules with alias:
- If the
locationends in/, end thealiaspath in/too. A mismatch produces paths like/srv/archivea.zip. - Prefer
rootwhen the directory layout on disk mirrors the URL layout. It is harder to get wrong. - With a regex
location,aliasneeds a capture group, so most people avoid that combination.
Index files and directory listings
The index directive takes a list of file names:
index index.html index.htm;Nginx tries them in order. If none exist and autoindex is off (the default), a directory request returns 403 Forbidden. That is the usual cause of a 403 on a directory that exists but has no index file.
For a download area, you can turn on a generated listing:
location /downloads/ {
alias /srv/archive/;
autoindex on;
autoindex_exact_size off;
autoindex_localtime on;
}autoindex_exact_size off shows sizes like 4.2M instead of exact bytes. autoindex_localtime on shows file times in the server's time zone rather than UTC. Enable autoindex only on directories you are happy to expose in full.
Custom error pages
error_page maps a status code to a page. The page is served by an internal redirect, so you usually mark its location as internal to stop clients from requesting it directly.
server {
listen 80;
server_name example.com;
root /var/www/example.com/html;
error_page 404 /errors/404.html;
error_page 500 502 503 504 /errors/50x.html;
location /errors/ {
internal;
}
location / {
try_files $uri $uri/ =404;
}
}The error pages live at /var/www/example.com/html/errors/ because they use the server's root.
Content types
Nginx picks the Content-Type header from the file extension using the table in mime.types. The main config includes it in the http context:
include /etc/nginx/mime.types;
default_type application/octet-stream;If a file has an unknown extension, Nginx uses default_type. Browsers treat application/octet-stream as a download, so a page with a missing mapping will download instead of display. Add the mapping to mime.types, or add a types block in the relevant context. Note that a types block replaces the inherited table for that context instead of extending it.
Caching headers for static assets
Browsers re-request files unless told otherwise. The expires directive sets both Expires and Cache-Control: max-age. A common pattern gives fingerprinted assets a long lifetime:
location ~* \.(css|js|png|jpg|jpeg|gif|svg|woff2)$ {
expires 30d;
add_header Cache-Control "public";
access_log off;
}Use long lifetimes only when file names change on every release, such as app.3f9a1c.js. For files that keep the same name, use a short lifetime or none, or users will keep seeing old versions.
Two gotchas apply here:
add_headerin alocationreplaces alladd_headerdirectives inherited from the outer levels. It does not add to them. If you set security headers at theserverlevel, repeat them inside anylocationthat has its ownadd_header.expiresalready sendsCache-Control: max-age. The extrapublicabove is optional and is shown only to illustrate the inheritance rule.
Efficient file delivery
Three directives control how the kernel and Nginx move file data. They go in the http, server, or location context:
sendfile on;
tcp_nopush on;
tcp_nodelay on;sendfile oncopies file data to the socket inside the kernel, skipping a copy through Nginx's memory.tcp_nopush onworks withsendfileand sends headers and the start of the file together in full packets.tcp_nodelay onstops small writes from waiting, which helps keepalive connections.
Most distribution packages already enable sendfile. Check your nginx.conf before adding duplicates. Compression and wider caching options are covered in the performance chapter.
Permissions and security of the document root
Many static-file failures come from file permissions, not from the Nginx configuration. The worker processes run as an unprivileged user, set by the user directive. On Debian and Ubuntu it is www-data. Check it with:
grep -E '^\s*user' /etc/nginx/nginx.confThat user needs two things:
- Execute (
x) permission on every directory in the path, from/down to the file. - Read (
r) permission on the file itself.
The namei tool shows the permissions at every step of a path:
namei -l /var/www/example.com/html/index.htmlIf one directory in the list lacks x for the worker user, Nginx logs Permission denied and returns 403. A typical fix gives the web content a safe owner and mode:
sudo chown -R root:www-data /var/www/example.com
sudo find /var/www/example.com -type d -exec chmod 755 {} \;
sudo find /var/www/example.com -type f -exec chmod 644 {} \;On systems with SELinux (RHEL, Fedora), correct Unix permissions are not enough. Files must carry the httpd_sys_content_t label, or reads fail with 403 even though the mode bits look correct. Use ls -Z to check the label.
Two further points protect the content:
- Do not put the document root where secrets live. Keep
.git,.env, and backup files out of it. - Deny dotfiles with a location block:
location ~ /\. {
deny all;
}Common errors
| Symptom | Likely cause | Check |
|---|---|---|
| 404 for a file that exists | Wrong `root`, or `alias` used where `root` was meant | Request log plus the error log line showing the path Nginx tried |
| 403 on a directory | No `index` file and `autoindex` is off | List the directory and compare with `index` |
| 403 on a file | Missing `x` on a parent directory, or SELinux label | `namei -l` and `ls -Z` |
| Page downloads instead of displaying | Missing MIME type | `curl -I` and read `Content-Type` |
| Old CSS after a deploy | Long `expires` on a file whose name did not change | Rename files with a hash, or shorten the lifetime |
| Security headers vanish on one location | `add_header` inheritance rule | Repeat headers in that `location` |
The error log states the exact path Nginx tried to open, which settles most root and alias questions. A line such as open() "/var/www/example.com/html/missing.css" failed (2: No such file or directory) tells you where Nginx looked.
Verifying your setup
After each change, test and reload, then check the response headers:
sudo nginx -t && sudo systemctl reload nginx
curl -I http://localhost/index.html
curl -I http://localhost/does-not-existThe first request should return 200 OK with Content-Type: text/html. The second should return 404 Not Found.
Exercise
A site uses root /var/www/site; at the server level. You add location /assets/ { alias /srv/static/; }. A request for /assets/logo.png returns 404. Which file path does Nginx read, and what is a likely cause if the file is at /srv/static/logo.png?
Show answer
Nginx reads /srv/static/logo.png, because alias replaces the matched /assets/ prefix. If that file exists but you still get 404, check the error log for the path Nginx actually tried. Likely causes are a missing trailing slash on an alias that does not match the location (for example alias /srv/static; producing /srv/staticlogo.png), or another location, such as a regex block for images, taking the request first and using the server-level root, which would look for /var/www/site/assets/logo.png.
Exercise
Your server sets add_header X-Frame-Options "DENY"; at the server level. After you add add_header Cache-Control "public"; inside a location for images, responses from that location no longer include X-Frame-Options. Why, and how do you fix it?
Show answer
A location that defines any add_header does not inherit add_header directives from outer levels. Fix it by repeating add_header X-Frame-Options "DENY"; inside that location. You can also remove the extra Cache-Control header, since expires already sets Cache-Control: max-age.