What is index directive in Nginx: Explanation and Usage
index directive in Nginx specifies the default file(s) to serve when a client requests a directory URL. It tells Nginx which file to look for, like index.html, so users see a webpage instead of a directory listing.How It Works
Imagine you walk into a library and ask for a book by the shelf name, but not a specific book title. The librarian then picks the most common or default book from that shelf to give you. Similarly, when a user visits a website URL that points to a folder (like example.com/blog/), Nginx uses the index directive to decide which file inside that folder to show, such as index.html or index.php.
This directive tells Nginx to look for one or more specified files in order. If the first file is not found, it tries the next one until it finds a file to serve. If none are found, Nginx may show a directory listing or an error, depending on configuration.
Example
This example shows how to configure Nginx to serve index.html or index.htm as the default files for a directory request.
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html index.htm;
}
}When to Use
Use the index directive whenever you want to control which file Nginx serves by default for directory URLs. This is common for websites where you want visitors to see a homepage or landing page without typing the full filename.
For example, if your site has multiple index files like index.html and index.php, you can list them in order of preference. This helps when migrating sites or supporting different content types.
It also improves user experience by hiding file names and making URLs cleaner and easier to remember.
Key Points
- The
indexdirective sets default files for directory requests. - Nginx checks files in the order listed until it finds one to serve.
- It helps create clean URLs without file extensions.
- Common default files are
index.htmlandindex.php. - If no index file is found, Nginx may show a directory listing or an error.