Search code examples
reactjsreact-router-dom

Why are my routes working locally but not on my live site?


I suspect this is not a code issue as the issue only occurs live and there are no console errors or anything else to indicate otherwise. If code examples are needed, I will share.

Objective: Allow visitors to view specific components on my site depending on the URL. This is achieved using react-router-dom.

It all works flawlessly locally but once it's live, it hits a 404 page. No errors when I test locally. I cannot recreate the problem locally so I don't really understand how to trouble shoot it.

Steps to recreate the problem:

  1. Navigate to https://wordplayideas.com/
  2. For every idea on the homepage, you can find a share button which you can click to go to a specific thing on the website(e.g. https://wordplayideas.com/russell-brands-mussell-bran) which displays as expected when going through the UI of the site. See below:

enter image description here

  1. Copy and paste that URL into any browser or simply refresh the page and it hits a specific 404 page. See below:

enter image description here

  1. If you manual put a typo into the URL locally, it directs to my custom 404 page which would at least be the expected behaviour on my live site. See below:

enter image description here


Solution

  • Thanks to Phil who responded to my initial question which eventually led me to finding the answer here.

    I may have asked the question incorrectly. Something I may have needed to include in my question is that I am deploying my site via cPanel. I would run npm run build and then upload the build files to the root folder of my website.

    The solution was to include a .htaccess file with the following in the root folder of my site. For most people this would be public_html.

    Inside the .htaccess file:

    <IfModule mod_rewrite.c>
    
      RewriteEngine On
      RewriteBase /
      RewriteRule ^index\.html$ - [L]
      RewriteCond %{REQUEST_FILENAME} !-f
      RewriteCond %{REQUEST_FILENAME} !-d
      RewriteCond %{REQUEST_FILENAME} !-l
      RewriteRule . /index.html [L]
    
    </IfModule>
    

    Once this file was uploaded, the routing worked just as it does locally. Hope it helps anyone else in a similar situation.