What is root directive in Nginx: Explanation and Example
root directive in Nginx sets the base directory where Nginx looks for files to serve for a given request. It tells Nginx the folder path to find website files like HTML, CSS, or images when a client asks for them.How It Works
The root directive in Nginx works like telling a waiter in a restaurant where the kitchen is located. When a customer orders a dish, the waiter knows exactly where to go to get it. Similarly, when a user requests a webpage, Nginx uses the root path as the starting point to find the requested file on the server.
For example, if the root is set to /var/www/html and the user requests /index.html, Nginx looks for the file at /var/www/html/index.html. This helps Nginx serve the correct files quickly and efficiently.
Example
This example shows how to set the root directive inside a server block to serve files from a specific folder.
server {
listen 80;
server_name example.com;
root /var/www/html;
location / {
try_files $uri $uri/ =404;
}
}When to Use
Use the root directive whenever you want to tell Nginx where your website files are stored on the server. It is essential for serving static files like HTML pages, images, CSS, and JavaScript.
For example, if you have multiple websites on one server, each site can have its own root path to serve files from different folders. This keeps files organized and ensures Nginx serves the right content for each domain or subdomain.
Key Points
- root sets the base folder for serving files.
- It works with the requested URL to find the exact file.
- Commonly used inside
serverorlocationblocks. - Helps organize multiple sites on one server by setting different roots.