React Router如何移除URL中的#符号?
Hey there! I’ve dealt with this exact frustration before—those # symbols in URLs can feel clunky and unprofessional. Let’s break down how to fix this, depending on which version of React Router you’re using.
For React Router v6 (Latest Version)
In v6, if you followed older tutorials you might be using HashRouter, but you’ll want to switch to browser-based routing instead to ditch the #:
Replace
HashRouterwithcreateBrowserRouterandRouterProvider
Here’s what your root setup might look like before:import { HashRouter, Routes, Route } from 'react-router-dom'; function App() { return ( <HashRouter> <Routes> <Route path="/user" element={<UserPage />} /> </Routes> </HashRouter> ); }And here’s the updated version for clean URLs:
import { createBrowserRouter, RouterProvider, Routes, Route } from 'react-router-dom'; const router = createBrowserRouter([ { path: '/user', element: <UserPage />, }, ]); function App() { return <RouterProvider router={router} />; }
For React Router v5 and Earlier
Older versions use a simpler component swap—just replace HashRouter with BrowserRouter:
Before:
import { HashRouter, Switch, Route } from 'react-router-dom'; function App() { return ( <HashRouter> <Switch> <Route path="/user" component={UserPage} /> </Switch> </HashRouter> ); }
After:
import { BrowserRouter, Switch, Route } from 'react-router-dom'; function App() { return ( <BrowserRouter> <Switch> <Route path="/user" component={UserPage} /> </Switch> </BrowserRouter> ); }
Critical Note: Server Configuration
Wait a second—if you just swap the router and refresh the page, you’ll probably get a 404 error! That’s because browser-based routing relies on your server serving the index.html file for all routes (since React handles routing client-side).
Here’s how to fix this for common setups:
- Create React App: Add a
_redirectsfile in yourpublicfolder with this line:/* /index.html 200 - Nginx: Add this to your server block:
location / { try_files $uri $uri/ /index.html; } - Apache: Create an
.htaccessfile in your root directory with:RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
Once you’ve updated your router and configured the server, your URLs will look clean like example.com/user instead of example.com#/user!
内容的提问来源于stack exchange,提问作者Jeyanth Kanagaraj

