Nginx · The edge of your stack
How does Nginx choose between competing locations?
Short answer
Nginx checks the exact match first, remembers the longest prefix, then evaluates regexes in order unless the winning prefix used ^~. If no regex matches, the remembered prefix is used.
The matching algorithm is the source of many routing bugs. It is not simply the longest string or the first block in the file. Exact matches win immediately, a ^~ prefix suppresses regex checking, and otherwise regexes are tried in config order.
location = /static/app.js {
return 200 "exact";
}
location ^~ /static/ {
return 200 "prefix";
}
location ~* \.js$ {
return 200 "regex";
}
location / {
return 200 "fallback";
}The evaluation order
- Find and use an exact = match immediately
- Record the longest matching prefix location
- If that prefix has ^~, use it and skip regexes
- Otherwise test regex locations in the order they appear and use the first match
- If no regex matches, use the remembered prefix location
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Why did a regex location not run for a path under a ^~ location?
- 2What wins between a longer prefix and a matching regex?
- 3Do nested locations change the matching order?
- 4How would you debug which location handled a request?
Say it in the interview
Nginx first checks for an exact match. Then it finds the longest prefix and, if that prefix is marked with ^~, it stops there. Otherwise it evaluates regexes in file order and falls back to the remembered prefix if none match. Most surprises come from ^~ or from assuming a longer prefix beats a regex, so I test the real paths.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Nginx mock interview and get scored feedback on depth, clarity and confidence.