Web / NGINX Interview questions
What is the difference between try_files and rewrite directives?
Both directives affect how NGINX resolves a request internally, but they operate very differently.
| try_files | rewrite |
| Checks a list of file paths on disk in order, using the first that exists. | Rewrites the request URI using a regex pattern, without checking the filesystem. |
| Falls back to a named location or status code if nothing is found. | Can redirect back to the client or continue processing internally with the new URI. |
| Common for single-page apps: serve the file if it exists, else fall back to index.html. | Common for legacy URL migrations: map an old URL pattern to a new one. |
location / { try_files $uri $uri/ /index.html; }
A frequent mistake is reaching for rewrite to solve a problem that try_files handles more simply and efficiently, since rewrite involves regex evaluation on every request while try_files just checks the filesystem directly.
More Related questions...