Location matching priority order in Nginx - Time & Space Complexity
When nginx receives a request, it must decide which location block to use. This decision involves checking multiple location patterns.
We want to understand how the time to find the right location grows as the number of location blocks increases.
Analyze the time complexity of this nginx location matching snippet.
server {
location = /exact {
# exact match
}
location ^~ /prefix {
# prefix match
}
location ~* \.(gif|jpg)$ {
# regex match
}
location / {
# default catch-all
}
}
This snippet shows different types of location blocks nginx checks to find the best match for a request URL.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: nginx checks location blocks in a specific order: exact matches first, then prefix matches, then regex matches.
- How many times: It checks exact and prefix matches quickly, but regex matches may require testing multiple patterns one by one.
As the number of location blocks grows, nginx spends more time checking regex locations because it tests them one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 regex tests in worst case |
| 100 | About 100 regex tests in worst case |
| 1000 | About 1000 regex tests in worst case |
Pattern observation: The time grows roughly in direct proportion to the number of regex locations.
Time Complexity: O(n)
This means the time to find the matching location grows linearly with the number of regex location blocks.
[X] Wrong: "nginx checks all location blocks equally fast regardless of type."
[OK] Correct: Exact and prefix matches use fast lookups, but regex matches are tested one by one, which takes more time as their number grows.
Understanding how nginx matches locations helps you reason about request routing efficiency and server performance in real projects.
"What if we removed all regex locations? How would the time complexity of location matching change?"