Beginner Fundamentals

Serving Static Files with root and index

One of Nginx’s core jobs is serving static files. The root and index directives decide where files live and which file to return for a directory request.

The root Directive

root sets the base directory on disk. Nginx appends the request path to it:

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
}

A request for /images/logo.png is served from /var/www/example/images/logo.png.

The index Directive

When a request points to a directory (like /), Nginx looks for an index file:

index index.html index.htm;

Nginx tries each name in order and returns the first one it finds. So a request for / returns /var/www/example/index.html if it exists.

Putting It Together

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

try_files checks the file, then the directory, and returns 404 if neither exists. This avoids exposing internal errors.

root vs alias

root appends the full request path. If you need to map a location to a different folder without the path prefix, use alias instead. For most static sites, root is all you need.