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

Create-React-App站点Netlify部署后React Router功能异常求助

Fixing React Router Issues on Netlify for Your Create-React-App Site

Hey there! I’ve run into this exact React Router problem dozens of times when deploying single-page apps (SPAs) to Netlify—let’s get it sorted out quickly.

Why This Happens

When you directly visit a route like /about or refresh the page, Netlify tries to look for a physical file at that path (like /about.html), but your React app only has one entry point: index.html. Since that file doesn’t exist, you get an error. React Router handles routing client-side, so we need to tell Netlify to send all traffic to index.html first.

The Fix: Add a Redirect Rule

There are two easy ways to set this up—pick whichever you prefer:

Option 1: Use a _redirects File

  1. In your Create-React-App project, navigate to the public folder.
  2. Create a new file named _redirects (no file extension).
  3. Paste this line into the file:
    /*    /index.html   200
    
  4. Commit this file to your Git repository and redeploy to Netlify. Netlify will automatically detect and apply this rule.

Option 2: Use a netlify.toml Configuration File

  1. At the root of your project, create a file named netlify.toml.
  2. Add this configuration to the file:
    [[redirects]]
      from = "/*"
      to = "/index.html"
      status = 200
    
  3. Commit and redeploy—this achieves the same result as the _redirects file.

Quick Check for Your Route Setup

Looking at your Router code, using process.env.PUBLIC_URL is smart for handling subpath deployments. Just make sure:

  • If your site is deployed at Netlify’s root (e.g., your-site.netlify.app), PUBLIC_URL will be empty, so your routes work as-is.
  • If you’re deploying to a subpath (e.g., your-site.netlify.app/my-app), set the homepage field in your package.json to match that subpath (like "homepage": "/my-app").

Once you add the redirect rule and redeploy, refreshing pages or directly accessing routes should work perfectly—React Router will take over and render the correct component every time.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 20:22:32