0
0
NginxHow-ToBeginner · 4 min read

How to Configure Root for Static Files in Nginx

To configure root for static files in Nginx, use the root directive inside a location block pointing to your static files directory. This tells Nginx where to find the files to serve when a matching URL is requested.
📐

Syntax

The root directive sets the directory path where Nginx looks for files to serve. It is usually placed inside a server or location block.

  • root <path>; — sets the root directory.
  • location <pattern> { ... } — matches URL patterns.
  • The full file path served is root + URI.
nginx
location /static/ {
    root /var/www/html;
}
💻

Example

This example configures Nginx to serve static files from /var/www/html/static when the URL starts with /static/. The root directive points to /var/www/html, so Nginx appends the URI after /static/ to this path.

nginx
server {
    listen 80;
    server_name example.com;

    location /static/ {
        root /var/www/html;
        # Requests to /static/image.png serve /var/www/html/static/image.png
    }
}
Output
When you visit http://example.com/static/image.png, Nginx serves the file located at /var/www/html/static/image.png if it exists.
⚠️

Common Pitfalls

One common mistake is confusing root with alias. Using root appends the full URI to the root path, while alias replaces the location prefix. Also, forgetting the trailing slash in the location can cause unexpected file paths.

Wrong example:

location /static/ {
    root /var/www/html/static;
}

This causes Nginx to look for files at /var/www/html/static/static/filename, duplicating the static folder.

Correct example:

location /static/ {
    root /var/www/html;
}
📊

Quick Reference

DirectiveDescriptionExample
rootSets the base directory for requestsroot /var/www/html;
locationDefines URL pattern to matchlocation /static/ { ... }
aliasReplaces location prefix with pathalias /var/www/html/static/;

Key Takeaways

Use the root directive inside a location block to set the base directory for static files.
The full file path served is the root path plus the requested URI.
Avoid duplicating folder names by correctly matching location and root paths.
Remember root appends the URI, alias replaces the location prefix.
Always test your configuration with nginx -t before reloading.