You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

Nginx Configuration to Redirect All Subdirectories to Root index.html

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_files directive is the star of the show:
    • $uri first 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:

  1. Update the server_name and root values to match your domain and file path
  2. Test your config for syntax errors with nginx -t
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:18:31