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.

Advertisement

Problem:

The web server returns a 404 error message when we directly hit a sub URL of a production ReactJS application.

(Resolved) – React.JS 404 Error on Page Reload

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 web server running.

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

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

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

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

  • Amazon S3 (Static Website Hosting)

    If the application is hosted through Amazon s3 static website hosting. You need to configure index.html in the Error document.

    Go to the application S3 bucket -> Properties -> Static website hosting and set the Error document as showing in below image:

  • Amazon CloudFront

    In the case of using Amazon Cloudfront with an s3 bucket, You also need to configure the Error pages in Cloudfront.

    Edit the Cloudfront -> Error pages. Now create a custom error response for 404 to index.html. You can also do the same for the 403 error code.

Conclusion

This tutorial helped you to resolve the 404 error in the ReactJS production environment. Here we include the solution for fixing 404 errors in Nginx, Apache, Amazon S3 and CloudFront hosted applications.

Share.

7 Comments

Leave A Reply

Exit mobile version