Index directive in Nginx - Time & Space Complexity
When a web server uses the index directive, it looks for default files to show when a folder is requested.
We want to understand how the time to find these files grows as the list of possible files grows.
Analyze the time complexity of the following code snippet.
location / {
index index.html index.htm index.php;
}
This code tells nginx to check for files named index.html, then index.htm, then index.php in order when a folder is requested.
- Primary operation: Checking each file name in the index list one by one.
- How many times: Up to the number of files listed in the index directive.
As the number of files in the index list grows, nginx checks each file in order until it finds one that exists.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 file check |
| 3 | Up to 3 file checks |
| 10 | Up to 10 file checks |
Pattern observation: The number of file checks grows linearly with the number of files listed.
Time Complexity: O(n)
This means the time to find the index file grows directly with how many files nginx must check.
[X] Wrong: "nginx checks all index files at once, so time stays the same no matter how many files are listed."
[OK] Correct: nginx checks files one by one in order until it finds a match, so more files means more checks in the worst case.
Understanding how nginx searches for index files helps you think about how servers handle requests efficiently.
"What if nginx used a hash table to check index files instead of checking one by one? How would the time complexity change?"