How to redirect all request to index in react or angular using htaccess?
Asked Answered
A

1

9

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.

Aeneid answered 17/7, 2018 at 11:9 Comment(2)
If you're using react-router you don't need to use .htaccess. Just configura routes properlyUnhook
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.Aeneid
A
23

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]
Aeneid answered 18/7, 2018 at 10:25 Comment(3)
But, where we put those configurations? What do you mean with ht access? I am using vs Code and I have react project?Aspectual
@Aspectual It is a file used by the server. Check here, 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 <HashRouter> from react-router.Aeneid
Thanks, 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.Microscopium

© 2022 - 2024 — McMap. All rights reserved.