Nginx · The edge of your stack
How does try_files work?
Short answer
try_files checks paths in order and uses the first that exists. The final argument is a fallback URI, status code or named location and is used when none of the files exist.
try_files is the standard way to serve a file if present and otherwise route to an application or a fallback. It is common for single-page apps, where unknown paths must return index.html.
location / {
root /var/www/app;
try_files $uri $uri/ /index.html;
}
location /api/ {
try_files $uri @app;
}
location @app {
proxy_pass http://backend;
}Fallback forms
- A URI such as /index.html triggers an internal redirect and location matching runs again
- A named location such as @app forwards to an internal handler
- An equals code such as =404 returns that status directly
- The final fallback must exist or be a valid status or named location
Because the fallback URI is re-matched, a broad SPA fallback can accidentally swallow API or asset 404s. Put API and asset locations before the catch-all, or use more specific fallbacks.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens after try_files falls back to a URI?
- 2How do you prevent an SPA fallback from masking API 404s?
- 3When would you use =404 instead of a named location?
- 4Does try_files work with alias?
Say it in the interview
try_files checks each path in order and uses the first one that exists. The last argument is a fallback: a URI that causes an internal redirect, a named location, or a status code. I use it for SPAs but keep API and asset locations more specific so the fallback does not hide real 404s. I also remember that every check is a filesystem lookup.
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.