I am creating an application in react using react-router. Earlier I was doing the same with angular but in both cases, if a user bookmarks a URL and loads it directly. It will show 404 error. can we create such rule in htaccess so that the URL doesn't change but the request is passed to index.html.
Asked
Active
Viewed 7,393 times
8
-
If you're using react-router you don't need to use .htaccess. Just configura routes properly – Adolfo Onrubia Jul 17 '18 at 17:16
-
I have a route like /about. when I try to load domain.com/about directly, it gives me 404 error. all the routes are set properly. In angular, I could use hash routing. SSR is also possible in both but I want to do it without it. – Dhanraj Acharya Jul 18 '18 at 10:19
1 Answers
22
So after much googling and looking through many answers, I found below configuration for htaccess.
it is working as expected and redirects each requests to index.html and from there react router handles everything.
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html [L,QSA]

Dhanraj Acharya
- 473
- 1
- 4
- 15
-
But, where we put those configurations? What do you mean with ht access? I am using vs Code and I have react project? – blackman May 15 '20 at 12:06
-
1@blackman It is a file used by the server. Check here, http://www.htaccess-guide.com/ If you don't want to do this then you can use hash(#) URLs as well. In your case, you can use
from react-router. – Dhanraj Acharya May 25 '20 at 05:16 -
3Thanks, I needed to serve React App under uncontrolled server statically, so I needed to redirect all URI to server the `index.html` in `.htaccess` file. – KeitelDOG Jul 06 '20 at 15:20