skip to Main Content

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


  1. 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.

    <IfModule mod_rewrite.c>
        Options -MultiViews
    
        RewriteEngine On
    
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.html [QSA,L]
    </IfModule>
    

    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.

    Login or Signup to reply.
  2. 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 "/"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search