can't switch between pages in cPanel

Viewed 589

I'm new to web-hosting and cPanel, so please be nice to me... I have built a website using react and managed to upload its build file to cPanel. It seems to work fine, however, whenever I try to switch between pages, I get a 404 error, although the pages clearly exist (for example, when I press a button to switch to mydomainname.com/about-us). The switching works perfectly locally using react-router.. I would really appreciate it if someone could help me solve this problem! Thanks in advance!

3 Answers

This is because ReactJS uses client side routing.

To fix 404, create a .htaccess file and paste below contents and upload it to your site root. It should work.

RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

If the above did not work, try below (recommended by ReactJS team), either one of this should work

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

The switching works perfectly locally using react-router

Routing works fine with the inbuilt ReactJS web server but not with Apache web server. Also make sure you are using react router Link component to navigate between pages and not the html anchor (a) tag.

You have to redirect all the requests to your index.html. You can edit the .htaccess for that. use <Link> from react-router to make redirections.

Follow these steps and you will be fine

Specify your homepage in your package.json file like this

{
  "name": "yourappname",
  "homepage": "http://example.com",//add your domain here line
  "private": true,
  "version": "0.0.0",
 }

2.Build your app by running yarn build or npm run build

3.Then copy the contents of your build folder and paste them on public_html folder in your cpanel

3.Go to your Cpanel file manager public_html folder and edit .htaccess file or create new one if it does not exist. and paste this there

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

Note the .htaccess for this should be at the same level with the contents of the build folder.

Save and your are done

Related