0
0
NginxHow-ToBeginner · 3 min read

How to Serve SPA Using try_files in Nginx

To serve a Single Page Application (SPA) with Nginx, use the try_files directive to first check if the requested file exists, and if not, redirect all requests to index.html. This ensures that client-side routing works correctly by always serving the SPA entry point for unknown paths.
📐

Syntax

The try_files directive in Nginx tries to serve files in the order you specify. If none of the files exist, it serves a fallback, usually index.html for SPAs.

  • try_files file1 file2 ... fallback;
  • file1, file2: paths to check if files exist
  • fallback: what to serve if none of the files exist (often /index.html)
nginx
try_files $uri $uri/ /index.html;
💻

Example

This example shows a minimal Nginx server block to serve an SPA. It tries to serve the requested file or directory. If not found, it serves index.html so the SPA can handle routing.

nginx
server {
    listen 80;
    server_name example.com;

    root /var/www/spa;
    index index.html;

    location / {
        try_files $uri $uri/ /index.html;
    }
}
Output
When you visit any URL, Nginx serves the file if it exists. If not, it serves /index.html, allowing the SPA to handle the route.
⚠️

Common Pitfalls

Common mistakes when using try_files for SPAs include:

  • Not including /index.html as the fallback, causing 404 errors on client-side routes.
  • Incorrect root path causing Nginx to fail finding files.
  • Using try_files $uri /index.html; without $uri/ can break requests for directories.

Correct usage ensures all unknown routes load index.html for SPA routing.

nginx
location / {
    # Wrong: missing $uri/ fallback
    try_files $uri /index.html;
}

location / {
    # Right: includes directory check
    try_files $uri $uri/ /index.html;
}
📊

Quick Reference

DirectivePurposeExample
try_filesChecks files in order, serves fallback if none foundtry_files $uri $uri/ /index.html;
rootSets the root directory for filesroot /var/www/spa;
indexDefault file to serveindex index.html;
location /Defines handling for all requestslocation / { try_files $uri $uri/ /index.html; }

Key Takeaways

Use try_files with $uri, $uri/, and /index.html to serve SPAs correctly.
Always set the root directive to your SPA's build directory.
The fallback to /index.html enables client-side routing to work.
Check your Nginx config syntax and reload after changes.
Avoid missing the directory check ($uri/) to prevent broken routes.