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.

2
  • If you're using react-router you don't need to use .htaccess. Just configura routes properly Commented Jul 17, 2018 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. Commented Jul 18, 2018 at 10:19

1 Answer 1

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]
Sign up to request clarification or add additional context in comments.

3 Comments

But, where we put those configurations? What do you mean with ht access? I am using vs Code and I have react project?
@blackman 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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.