How to Handle SPA Routing in Nginx: Fix and Best Practices
SPA routing in nginx, configure it to serve index.html for all routes that do not match a file or directory. This is done by using the try_files directive with $uri, $uri/, and fallback to /index.html.Why This Happens
Single-page applications (SPAs) use client-side routing, meaning the browser handles navigation without asking the server for new pages. When you refresh or directly visit a route like /profile, nginx tries to find a matching file or folder. If it doesn't exist, nginx returns a 404 error because it doesn't know to serve the SPA's index.html for these routes.
server {
listen 80;
server_name example.com;
root /var/www/spa;
location / {
try_files $uri $uri/ =404;
}
}The Fix
Change the try_files directive to serve index.html when the requested file or directory is not found. This tells nginx to fallback to the SPA entry point, allowing the client-side router to handle the route.
server {
listen 80;
server_name example.com;
root /var/www/spa;
location / {
try_files $uri $uri/ /index.html;
}
}Prevention
Always configure your web server to fallback to index.html for SPA routes to avoid 404 errors on refresh or direct URL access. Use try_files in nginx to check for files first, then fallback. Test your SPA routes after deployment to confirm correct behavior.
Keep your index.html and static assets organized and use caching headers wisely to improve performance.
Related Errors
Other common errors include:
- 404 on static assets: Ensure static files like JS and CSS are correctly referenced and exist in the
rootdirectory. - Incorrect base href: In your SPA, the
<base href="/">tag must match your deployment path. - Cache issues: Old cached files can cause routing problems; clear browser cache or configure cache busting.