Skip to content

How to Use Nginx try_files Directive

DodaTech Updated 2026-06-24 2 min read

try_files provides flexible file serving with fallback options. It is essential for SPAs and dynamic file resolution. This guide walks through the specific troubleshooting steps to diagnose and resolve try_files issues.

Before You Begin

Before you begin, be sure to have the following in place:

  • A Linux server with the relevant software installed
  • Access to the command line interface
  • Appropriate permissions (root or sudo)

Quick Fix

Wrong

location / {\n    root /var/www/app;\n}

Wrong: Serving files directly without fallback

location / {\n    root /var/www/app;\n    try_files $uri $uri/ /index.html;\n}

Right: try_files with fallback to index.html for SPA routing

Output

try_files configured:\n  Check: $uri (exact file)\n  Check: $uri/ (directory)\n  Fallback: /index.html

Prevention

To avoid future issues, follow these best practices:

  • Use try_files for single-page application (SPA) routing
  • Order files by preference -- first match wins
  • Use $uri/ for directory index handling
  • Use =404 as final argument to return 404 if nothing matches
  • Combine with named locations for complex fallback logic

DodaTech Tools

For further assistance with any of the above issues, consider using DodaTech consulting services or DodaTech tutorials for more in-depth guidance.

Common Mistakes with try files

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world NGINX code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

How does try_files work?|||Nginx checks each argument in order. If the file exists, it is served. If none exist, the last argument is used as an internal redirect.
Why do SPAs need try_files? Browser-side routing (React, Vue, Angular) uses URLs like /profile. The server must serve index.html for these paths since the actual file does not exist.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro