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

React Router应用部署至服务器子目录后嵌套路由直接访问404及HashRouter路径格式异常的解决方案咨询

Fixing Nested Routing 404s for React Router Deployed to a Subdirectory

Hey there, let's sort out this frustrating nested routing 404 issue you're facing. You've already nailed the client-side config bits (setting homepage and basename), but the missing piece is server-side routing rules—since React is a single-page app (SPA), your server doesn't know to route all nested paths back to your app's index.html. Here's how to fix it step by step:

1. Double-Check Your React & React Router Config

First, confirm you have these set up correctly (you mentioned you did, but it's good to verify):

  • In package.json, ensure your homepage is set with a trailing slash:
    "homepage": "/react-app/"
    
  • Wrap your app with BrowserRouter and include the basename prop (this ensures all client-side routes are prefixed with /react-app):
    import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
    
    function App() {
      return (
        <Router basename="/react-app">
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/home" component={Dashboard} />
            {/* Add other routes here—note paths don't include /react-app */}
          </Switch>
        </Router>
      );
    }
    

2. Configure Your Server to Rewrite Routes

This is the critical part. When a user directly visits https://website.com/react-app/home, your server tries to find a physical file at /react-app/home—which doesn't exist. You need to tell it to send all requests under /react-app to index.html instead. Here's how to do this for common servers:

Nginx

Edit your Nginx config file (usually in /etc/nginx/sites-available/ or similar) and add a location block for your subdirectory:

location /react-app {
  root /path/to/your/website/files;
  try_files $uri $uri/ /react-app/index.html;
}

Reload Nginx after saving: sudo systemctl reload nginx

Apache

Create a .htaccess file in your /react-app directory with these rules:

RewriteEngine On
RewriteBase /react-app/
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /react-app/index.html [L]

Make sure Apache's mod_rewrite module is enabled.

IIS

Create a web.config file in your /react-app directory:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <rewrite>
      <rules>
        <rule name="React Routes" stopProcessing="true">
          <match url=".*" />
          <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            <add input="{REQUEST_URI}" pattern="^/(react-app)" negate="false" />
          </conditions>
          <action type="Rewrite" url="/react-app/index.html" />
        </rule>
      </rules>
    </rewrite>
  </system.webServer>
</configuration>

Static Hosting Platforms (Netlify/Vercel)

  • Netlify: Create a _redirects file in your project's public folder with this line:
    /react-app/* /react-app/index.html 200
    
  • Vercel: Add a vercel.json file to your project root:
    {
      "rewrites": [
        { "source": "/react-app/(.*)", "destination": "/react-app/index.html" }
      ]
    }
    

3. Fixing HashRouter's Path Format

If you prefer using HashRouter to avoid server config changes, let's fix that path issue you mentioned (getting https://website.com/react-app#/ instead of https://website.com/react-app/#/):

The missing trailing slash is likely because your server isn't redirecting https://website.com/react-app to https://website.com/react-app/. If you can't adjust server settings, try these steps:

  • Keep your homepage in package.json set to /react-app/ (with the trailing slash)
  • Use HashRouter without the basename prop (since your app is already deployed under /react-app/):
    import { HashRouter as Router, Route, Switch } from 'react-router-dom';
    
    function App() {
      return (
        <Router>
          <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/home" component={Dashboard} />
          </Switch>
        </Router>
      );
    }
    

This should generate paths like https://website.com/react-app/#/home as expected.

Final Notes

  • Always test directly accessing nested routes after deploying changes—don't just rely on in-app navigation.
  • If you're using Create React App, run npm run build after updating configs, then deploy the build folder to your /react-app server directory.

内容的提问来源于stack exchange,提问作者BryceBy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 07:32:29