0
0
NginxConceptBeginner · 3 min read

What is index directive in Nginx: Explanation and Usage

The 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.

nginx
server {
    listen 80;
    server_name example.com;

    location / {
        root /var/www/html;
        index index.html index.htm;
    }
}
Output
When a user visits http://example.com/, Nginx serves /var/www/html/index.html if it exists; if not, it tries /var/www/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 index directive 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.html and index.php.
  • If no index file is found, Nginx may show a directory listing or an error.

Key Takeaways

The index directive tells Nginx which file to serve by default in a directory.
You can list multiple files in order of preference for Nginx to try.
It helps create clean URLs by hiding file names from users.
If no index file is found, Nginx may show a directory listing or an error.
Use it to control the homepage or landing page for your website directories.