I am experiencing problems with redirecting 404 errors for URL paths generated by React on an Apache server.
Scenario:
Let’s say I have some URL generated by React Router: www.somewebsite.com/apps
Problem:
How do I redirect back to www.somewebsite.com/apps if the end-user clicks on refresh?
What I have tried:
So far, I am able to redirect the user to www.somewebsite.com. I just need to get the path before the redirect.
2
Answers
Set an Apache rewrite rule to rewrite all requests to your React app (index.html).
Put this in your vhost config or a .htaccess file.
Now, when a user presses refresh (or visits directly) on any route like
/apps
, your React app will be loaded and the router will display the relevant route.Note: the
RewriteCond
excludes static files from being rewritten which is necessary.In my react case this error happened only when I navigate to links with more than one slash:
E.g.
http://www.abc.com/support works with Apache rewrite rule but http://www.abc.com/support/[email protected] fails
My solution was to open index.html and make all links point back to main domain.
Replace
"./"
with
"/"