Search code examples
reactjswebcpanel

can't switch between pages in cPanel


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!


Solution

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