Nginx配置:将任意/不存在的子目录重定向至根目录index.html
Hey there! I’ve helped a bunch of folks set up this exact Nginx config for single-page apps (SPAs) and static sites where they want all subdirectory requests—even non-existent ones—to land on the root index.html. Let me walk you through the best way to do this.
First, here’s the practical, production-ready config you’ll want to drop into your server block. This balances serving static assets (like CSS, JS, images) normally while routing all other requests to your root index:
server { listen 80; server_name your-domain.com; # Swap this with your actual domain root /var/www/your-site-folder; # Replace with your site's root file path index index.html; # Serve static assets directly (with long cache times for performance) location ~* \.(css|js|png|jpg|jpeg|gif|ico|svg|woff|woff2)$ { expires 1y; add_header Cache-Control "public, immutable"; } # Route all other requests to index.html location / { try_files $uri $uri/ /index.html; } }
Let’s break down what’s happening here:
- The
try_filesdirective is the star of the show:$urifirst tries to serve the exact file requested (so if someone hits/styles.css, it serves that file instead of redirecting)$uri/checks if the requested path is a directory (and would serve that directory’s index if it existed)- If neither of those work (or if you’re targeting a subdirectory meant for client-side routing), it falls back to
/index.html
If you want to force all subdirectories (even existing ones) to redirect:
If you don’t need to serve any subdirectory content at all (uncommon, but possible), you can use a rewrite rule instead:
location / { rewrite ^/.+$ /index.html last; }
This will send every request that’s not the root directly to index.html, no exceptions.
Final Steps:
- Update the
server_nameandrootvalues to match your domain and file path - Test your config for syntax errors with
nginx -t - Reload Nginx to apply changes:
sudo systemctl reload nginx(on Linux systems)
This setup is perfect for React, Vue, Angular, or any SPA where client-side routing handles all page navigation—no more 404s when users refresh a subdirectory page!
内容的提问来源于stack exchange,提问作者Raleigh Guevarra

