skip to Main Content

I’m using react with react-router to build a website. I have hosted this website on a shared cPanel hosting from Godaddy. It is a linux with Apache server.

The application works fine on natural link routing but when I reload the page on my server it gives a 404 not found. While I understand the problem and made changes in .htaccess file to redirect to index.html on each request, this works only for top level routes.

Example: This works for www.mysite.com/about and www.mysite.com/users when reloading. But this does not work for sub routes like www.mysite.com/users/john when reloading.

This is my configuration on .htaccess file

Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

I have no idea about what or how the .htaccess file contents does stuff and this is a configuration I took from other Stack Overflow answer. I do not understand how to make changes to this config to support sub routes as well.

Below is the error on console when I reload on sub routes

Uncaught SyntaxError: Unexpected token '<' (at bundle.js:1:1)

Any help on this is much appreciated!

PS: This works fine on the local webpack dev server with the historyApiFallback value set to true

Versions:

"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.4.3",

2

Answers


  1. make sure that, you have <base href="/" /> in head of index.html

    Login or Signup to reply.
  2. If you are using React.

    If issue still persists after adding base href="/" in head of public/index.html

    so 1st remove base href="/"

    You can try 2 solutions from here:

    1> Replace "BrowserRouter" with "HashRouter". (just you will find an extra "#" gets added in your base route)

    2> update or create a 404.html file in public Directory: e.g.

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css"
          integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">
          <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;700&display=swap" rel="stylesheet">
      
        <title>Your Title</title>
        <script type="text/javascript">
          var segmentCount = 1;
          var l = window.location;
          l.replace(l.protocol + '//' + l.hostname + (l.port ? ':' + l.port : '') );
        </script>
      </head>
      <body>
      </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search