Once you make a production build of your ReactJS application. It creates an index.html file, which serves the entire application. All the requests must be hist to index.html first then the React Router serves the content based on the query in the URL. When we access the application with the main URL, it hits index.html and works fine. In case, you directly access one sub URL in the browser, the webserver doesn’t find any file with that name. In that case, a 404 error message is returned to the user.

Problem:

A 404 error message is returned by the webserver when we directly hit a sub URL of a production ReactJS application.

(Resolved) – ReactJS 404 Error on Page Reload Error Code 404 General Articles react ReactJs

Solution:

A simple solution is to route all requests to the index.html file. Rest the React router will handle this.

Update your server configuration based on the webserver running.

1. Nginx Users

The Nginx users can edit the server block (virtual host) configuration file and add the following snippet. This will route all the requests to the index.html file.

#Add this in Nginx server block
location / {
  ...
  try_files $uri.html $uri $uri/ /index.html;
  ...
}

Save the file and restart the Nginx service.

2. Apache Users

If the react application is hosted on an Apache webserver. Then you can add a .htaccess file at the root of your site and add the following snippet.

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

Make sure the Apache rewrite module is enabled on your system.

Conclusion

This tutorial helped to resolve the 404 error in the ReactJS production environment.