I’m using react with react-router to build a website. I have hosted this website on a shared cPanel hosting from Godaddy. It is a linux with Apache server.
The application works fine on natural link routing but when I reload the page on my server it gives a 404 not found. While I understand the problem and made changes in .htaccess
file to redirect to index.html
on each request, this works only for top level routes.
Example: This works for www.mysite.com/about
and www.mysite.com/users
when reloading. But this does not work for sub routes like www.mysite.com/users/john
when reloading.
This is my configuration on .htaccess
file
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
I have no idea about what or how the .htaccess
file contents does stuff and this is a configuration I took from other Stack Overflow answer. I do not understand how to make changes to this config to support sub routes as well.
Below is the error on console when I reload on sub routes
Uncaught SyntaxError: Unexpected token '<' (at bundle.js:1:1)
Any help on this is much appreciated!
PS: This works fine on the local webpack dev server with the historyApiFallback
value set to true
Versions:
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3",
2
Answers
make sure that, you have
<base href="/" />
in head of index.htmlIf you are using React.
If issue still persists after adding base href="/" in head of public/index.html
so 1st remove base href="/"
You can try 2 solutions from here:
1> Replace "BrowserRouter" with "HashRouter". (just you will find an extra "#" gets added in your base route)
2> update or create a 404.html file in public Directory: e.g.