DEV Community

Cover image for how to prevent not found error when reloaded in a website when hosted in cpanel
K-kibet
K-kibet

Posted on

how to prevent not found error when reloaded in a website when hosted in cpanel

Got it πŸ™‚ β€” you're hosting your website on cPanel and experiencing a 404 Not Found error when you reload a page or directly access a nested route (e.g., /dashboard, /blog/post/1, etc.).

This usually happens when you're using a single-page application (SPA) built with React, Vue, Angular, or Vite, because the browser tries to directly fetch the nested route from the server, but the server doesn't know how to handle it and returns a 404 error.

I'll show you how to fix it by setting up .htaccess rules.


Solution β€” Use .htaccess to Redirect All Requests to index.html

Steps:

  1. Login to your cPanel
  • Go to File Manager.
  • Navigate to your public_html folder (or the folder where your site is hosted).
  1. Enable Hidden Files
  • Click Settings in the top-right corner.
  • Enable Show Hidden Files so you can see .htaccess.
  1. Create or Edit the .htaccess File
  • If .htaccess doesn’t exist, create a new file named .htaccess.
  • Add the following rules:
   <IfModule mod_rewrite.c>
     RewriteEngine On
     RewriteBase /
     RewriteRule ^index\.html$ - [L]
     RewriteCond %{REQUEST_FILENAME} !-f
     RewriteCond %{REQUEST_FILENAME} !-d
     RewriteRule . /index.html [L]
   </IfModule>
Enter fullscreen mode Exit fullscreen mode

What this does:

  • If the requested file or folder exists, it will be served normally.
  • If it doesn't exist (like /dashboard), Apache will serve index.html instead β€” allowing your SPA to handle routing.
  1. Clear Browser Cache
  • Press Ctrl + Shift + R or hard refresh the site.
  1. Make Sure mod_rewrite Is Enabled
  • Most cPanel servers have mod_rewrite enabled by default.
  • If you still get 404 errors, contact your hosting provider to confirm.

For React + Vite Projects

If you’re using Vite (since you mentioned using it before), make sure your vite.config.js also has this:

export default {
  base: '/',
}
Enter fullscreen mode Exit fullscreen mode

Then rebuild your project:

npm run build
Enter fullscreen mode Exit fullscreen mode

Upload the dist folder to public_html.


Alternative: Use cPanel's Redirects

  • Go to cPanel β†’ Redirects.
  • Set up a redirect from example.com/* β†’ example.com/index.html.
  • But .htaccess is the recommended way β€” it's faster and cleaner.

Summary

  • Place an .htaccess file in public_html.
  • Add rewrite rules to redirect unknown routes to index.html.
  • Make sure mod_rewrite is enabled.
  • Rebuild and re-upload if using Vite/React/Angular.

Top comments (0)