React路由报错:index.html未匹配路由及打包部署困惑
Let's break down what's going on here and fix that routing issue step by step:
The Core Problem
When you run yarn start locally, your dev server (like webpack-dev-server) serves the app from the root path (/) and automatically handles fallback routing for single-page apps. But when you deploy to http://www.shadyab.com/test20/, your app is running under a subdirectory—not the root. Your React Router setup isn't aware of this subpath, and your server isn't configured to redirect all requests to index.html (a critical requirement for React Router to work properly after page refreshes or direct route visits).
Step 1: Update React Router with basename
React Router needs to know it's operating under a subdirectory. If you're using BrowserRouter, add the basename prop pointing to your subpath:
import { BrowserRouter } from 'react-router-dom'; ReactDOM.render( <BrowserRouter basename="/test20"> <App /> </BrowserRouter>, document.getElementById('root') );
This tells React Router to prefix all your routes with /test20, so it aligns with the server's subdirectory structure.
Step 2: Configure Webpack's publicPath
Make sure your build outputs assets with the correct subdirectory path. Update your webpack configuration:
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { // ... other existing configs output: { path: path.resolve(__dirname, 'dist'), filename: '[name].bundle.js', // Set publicPath to your subdirectory publicPath: '/test20/' }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', filename: 'index.html' }) ] };
If you're using Create React App instead of a custom webpack setup, add a homepage field to your package.json instead—this will auto-configure the correct publicPath during build:
{ "homepage": "/test20/" }
Step 3: Configure Your Server to Fallback to index.html
React is a single-page app: when you refresh a route like /test20/about, your server tries to find a physical file at that path (which doesn't exist) instead of sending index.html. Fix this with server-specific settings:
For Nginx:
Update your server block to include:
location /test20 { root /path/to/your/dist/folder; // Redirect all requests to index.html try_files $uri $uri/ /test20/index.html; }
For Apache:
Create a .htaccess file in your dist/test20 directory with:
RewriteEngine On RewriteBase /test20/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /test20/index.html [L]
Step 4: Rebuild and Redeploy
After making these changes, run npm run build again, upload the updated dist folder to your server, and test the app. The routing should now work correctly—whether you navigate via app links or refresh the page.
内容的提问来源于stack exchange,提问作者S.M_Emamian

