I'm using routes with createBrowserRouter
and everything is fine locally but when I upload my website build and make my site live, when I enter the url manually or refresh the page, I'm getting 404 Error
, I've researched on various stack questions but didn't get the answer on how exactly solve this issue when you're using createBrowserRouter
instead of <Routes> //Routes here </Routes>
.
I also tried spa-github-pages where you make 404.html file in /public
and copy the script mentioned in the github repo, but this solution also didn't work.
I'm using a simple method of routing with latest react-router version. I know its a client side routing
issue but how to solve it exactly with react-router v6.14.0
Also another problem is when I get 404 Not Found error I can't see my <404NotPage />
well designed component page.
Here is my code:-
App.js
import { createBrowserRouter, RouterProvider } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/",
element: <Home />,
},
{
path: "about-us",
element: <About />,
},
{
path: "*",
element: <NotFound />, // also can't see this page
},
])
export default function App() {
return <RouterProvider router={router} />;
}
Add .htaccess
file and add below code if you are hosting your build on Apache server (cpanel)
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase / RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule . /index.html [L]
</IfModule>