Sub topic 4
Serving static files directly, sending the rest to the app
This chapter assumes you can read an Nginx server block and know what root and location do from the earlier chapters. It also assumes you have a PHP or Python app that already runs behind some server process. The goal here is the split of work. Nginx answers requests for files that exist on disk, and the application answers everything else.
Why split the work
A static file is a response that is the same for every visitor and can be read straight from disk. Examples are CSS, JavaScript, images, fonts, and downloads. A dynamic response is built by your code for each request, such as a rendered page or a JSON API reply.
Nginx serves static files with very little CPU and memory. It uses the kernel's sendfile call and handles thousands of connections in a few worker processes. A PHP-FPM worker or a Gunicorn worker is much more expensive, and each one handles a single request at a time. If those workers spend their time sending logo.png, they are not available for real application work.
Serving static files directly gives you three benefits:
- Application workers are free for dynamic requests.
- Files get correct cache headers,
Content-Length, and range support without extra code. - A request for a file that does not exist is rejected at the web server instead of starting your framework.
The core tool: try_files
try_files checks a list of candidates in order. It serves the first one that exists. The last argument is different. It is not checked against the disk. It is either a fallback URI or a status code.
location / {
try_files $uri $uri/ /index.php?$query_string;
}For a request to /css/site.css, Nginx builds the path from root plus $uri. If the file exists, it is served. If not, Nginx tries the same path as a directory. If that also fails, it performs an internal redirect to /index.php?$query_string, and the PHP location handles it. The browser URL does not change.
This is the standard pattern for front-controller applications such as Laravel or WordPress with pretty URLs. Every route like /posts/42 has no file on disk, so it falls through to index.php. The router inside your application then decides what to do.
A complete PHP example
This is the server block from the spine of this tutorial. It serves static files from public and sends the rest to PHP.
server {
listen 80;
server_name example.com;
root /var/www/example/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php8.3-fpm.sock;
}
location ~ /\.(?!well-known) {
deny all;
}
}The socket path and the snippets/fastcgi-php.conf file are Debian and Ubuntu conventions. The PHP version in the socket name must match what you installed. The later chapter on FastCGI explains the location ~ \.php$ block. Here, only the location / block decides between static and dynamic.
The root points at public, not at the project directory. Source code, .env files, and vendor stay outside the web-visible tree, so no configuration mistake can serve them.
A complete Python example
A Python app has no PHP-style front controller, and Gunicorn does not serve files. You make the split explicit with a /static/ prefix and a proxy fallback.
server {
listen 80;
server_name example.com;
location /static/ {
alias /srv/myapp/static/;
}
location / {
proxy_pass http://unix:/run/gunicorn/app.sock;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}Anything under /static/ comes from disk. Everything else goes to Gunicorn. Frameworks such as Django have a command that copies all static assets into one directory (collectstatic), so the alias target is that directory. The proxy_pass and header lines are covered in the reverse proxy and forwarded headers chapters.
root versus alias
These two directives build file paths differently, and mixing them up is a very common cause of 404 errors.
| Directive | How the path is built | Request `/static/app.css` with the directive below |
|---|---|---|
| `root /srv/myapp;` | `root` + full URI | `/srv/myapp/static/app.css` |
| `alias /srv/myapp/assets/;` | `alias` replaces the matched location prefix | `/srv/myapp/assets/app.css` |
With root, the location prefix stays in the file path. With alias, the matched prefix is swapped for the alias value. Follow two rules:
- When the URL path mirrors the directory layout, use
root. - When it does not, use
alias, and give the location and the alias target the same trailing slash. A mismatch such aslocation /staticwithalias /srv/myapp/static/;produces paths with a doubled or missing slash.
Which location wins
Nginx picks one location per request in this order:
- An exact match,
location = /path. - The longest matching prefix that carries the
^~modifier. If it matches, regex locations are skipped. - The first matching regex (
~or~*), in file order. - The longest matching plain prefix.
Consider a PHP site with location /static/ and location ~ \.php$. A request for /static/upload.php matches both. The plain prefix is only a candidate, and the regex wins, so PHP would run that file. To keep a directory purely static, use the ^~ modifier:
location ^~ /static/ {
alias /srv/myapp/static/;
expires 30d;
}Now no regex location can take over requests under /static/.
Cache headers for static files
Browsers can reuse a downloaded file if you tell them how long it stays valid. The expires directive sets both Expires and Cache-Control: max-age.
location ^~ /static/ {
alias /srv/myapp/static/;
expires 30d;
add_header Cache-Control "public";
access_log off;
}Long lifetimes are only safe when file names change with their content, for example app.3f9a1c.css. Most build tools and Django's ManifestStaticFilesStorage can do this. Without versioned names, visitors may see stale CSS for a month.
Two details cause trouble. First, add_header in a location replaces any add_header lines inherited from the server block. It does not add to them. If you set security headers at server level, repeat them in this location. Second, access_log off removes these requests from your logs, which helps with noise but hides them when you debug.
Edge cases
- Missing static files fall through to the app. With
try_files $uri /index.php, a missing/img/old.pngreaches PHP, and your framework renders its 404 page. That costs a PHP worker. For asset directories, usetry_files $uri =404;so Nginx returns the 404 itself. - Directory requests.
$uri/plusindexservesindex.htmlfor directories. Python apps often leave this out so that/goes to the app. - Python apps that also need
robots.txtorfavicon.ico. Set arootand use a named location as the fallback:
server {
listen 80;
server_name example.com;
root /srv/myapp/public;
location ^~ /static/ {
alias /srv/myapp/static/;
expires 30d;
try_files $uri =404;
}
location / {
try_files $uri @app;
}
location @app {
proxy_pass http://unix:/run/gunicorn/app.sock;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}A named location starts with @. It cannot be requested directly and is reachable only through try_files or similar internal redirects. Do not add a URI to proxy_pass inside it.
- Permissions. The Nginx worker user (
www-dataon Debian and Ubuntu) needs execute permission on every directory in the path and read permission on the files. A file that exists but is unreadable gives a 403, not a 404.
Testing the split
Check the syntax, reload, then request one static file and one dynamic URL. The response headers show which side answered.
sudo nginx -t
sudo systemctl reload nginx
curl -I http://example.com/static/app.css
curl -I http://example.com/does-not-exist
sudo tail -n 20 /var/log/nginx/error.logFor the static file, look for Content-Type: text/css, a Last-Modified header, and Cache-Control: max-age=2592000. For the missing URL, a 404 page styled like your application proves the request reached the app. A plain Nginx 404 page means Nginx answered. The error log records the file path Nginx tried, which settles any root versus alias doubt.
Exercise
Your config has location /static/ { root /srv/myapp/assets; }. The file /srv/myapp/assets/app.css exists, but curl -I http://example.com/static/app.css returns 404. Why, and what are two ways to fix it?
Show answer
With root, Nginx appends the full URI, so it looks for /srv/myapp/assets/static/app.css, which does not exist. Fix 1: use alias /srv/myapp/assets/; so the /static/ prefix is replaced. Fix 2: keep root and move or link the files so they sit in /srv/myapp/assets/static/. The error log line shows the exact path Nginx tried.
Exercise
A PHP site has location /static/ { ... } and location ~ \.php$ { ... }. Why can a request for /static/test.php still reach PHP-FPM, and how do you prevent it?
Show answer
Nginx prefers a matching regex location over a plain prefix location, so the .php regex wins. Change the prefix location to location ^~ /static/, which stops Nginx from checking regex locations once that prefix matches.