Nginx can serve static files directly: html, css, png, and so on. We'll look at how that works, how to configure index files, and how to get the most performance out of it.
Root directory and index files
The root directive specifies the root directory used to look for a file. To build the path of the requested file, Nginx
appends the request URI to the root directory. The root directive can sit at any level of http {}, server {}, or location {}.
The index directive specifies the index file used when the request URI ends with a slash /. If the URI ends with a
slash / but the index file can't be found, Nginx returns a 404 (Not Found) page. The default index file is index.html.
server {
root /www/uploads;
#you can also define several index files.
index index.html index.htm;
location / {
#You can override the index file.
index index.html;
}
location /images/ {
#If the request URI is "/images/hero.png", Nginx fetches the file "/www/uploads/images/hero.png".
}
location ~ \.(mp3|mp4) {
#Redefining "root" overrides the previous "root".
#If the request URI is "/hd/video.mp4", Nginx fetches the file "/www/media/hd/video.mp4".
root /www/media;
}
}Checking that the requested file exists
The Nginx try_files directive checks whether the requested file or directory exists.
location / {
#the $uri variable holds the request URI.
#Nginx tries the first parameter, and if it doesn't exist, it tries the second, and so on.
#In this example, if no parameter exists, it returns a 404 page.
try_files $uri $uri/ $uri.html =404;
}Optimizing content delivery performance
The optimization is already there in the general nginx configuration, nginx.conf. These 4 lines are in that file:
http {
#...
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
}By default, Nginx copies files into a buffer before sending them. The sendfile directive tells Nginx to
skip that step and send the file directly.
The tcp_nopush directive lets Nginx send the response headers in a single packet right after the data block has been
obtained by sendfile(). Because of that, you can only enable this option if sendfile is in use.
By default, Nginx groups a number of small packets into a larger one and sends that packet with a 200 ms delay. This solves
the slowdown caused by a large number of requests over a slower connection, but for sending large static files
it isn't necessary. The tcp_nodelay directive turns that behavior off, and the persistent connection (keepalive connection) has to be
used with it.
