Sling Academy
Home/DevOps/NGINX & React Router error: 404 not found

NGINX & React Router error: 404 not found

Last updated: January 20, 2024

The Issue

Deploying a React Single Page Application (SPA) with NGINX often leads to a common issue: receiving a ‘404 not found’ for routes managed by React Router. The error occurs because NGINX doesn’t natively understand the client-side routing strategy employed by React Router. If you’re in this predicament, fear not. Our tutorial is a lifeline, extending curls of wisdom to pull you from the depths of HTTP status despair.

Solutions

Solution 1: NGINX Configuration Update

To direct traffic correctly, a common solution is to update your NGINX configuration so that all routes default to your index.html, allowing React Router to handle routing.

  1. Edit your nginx.conf file (typically located in /etc/nginx or /usr/local/nginx).
  2. Locate the server block for your application.
  3. Within the location block, update the try_files directive to serve index.html as a fallback.
  4. Restart NGINX to apply the changes.

 location / {
     try_files $uri /index.html;
 }
 

This approach is straightforward and directly compatible with SPA routing. However, be aware that this strategy might result in a slight loss of server-side efficiency, as all unresolved routes will load the entire app.

Solution 2: Error Page Handling

Another method is to direct 404 errors to your index.html, allowing React Router to manage the routing from there.

  1. Like the first solution, start by editing nginx.conf within the appropriate server block.
  2. Add or modify the error_page directive to point 404 errors to your root index.html.
  3. Ensure that the root directive is set to the location of your built React app.
  4. Restart NGINX to see the change.

 error_page 404 =200 /index.html;
 location / {
     root /path/to/your/react/app;
 }
 

This solution maintains separate server error handling, which can be beneficial for tracking and logging issues. But similar to the first solution, using this method may also load the full app for any missing route.

Solution 3: NGINX Map Directive

For a more nuanced approach, use the NGINX map directive to conditionally redirect based on the requesting URL.

  • Define a map directive at the http level in your nginx.conf.
  • Create a variable that maps nonexistent files or directories to a default route.
  • Refer to your new variable within the server block, using the try_files directive to default to index.html.
  • Reload to propagate your configurational evolution.
http {
     map $uri $route {
         ~*^/. 0;
         default 1;
     }
 }

server {
   location / {
       try_files $uri $uri/ $route =404;
       root /path/to/your/react/app;
   }
}

By leveraging map, we blend precision with flexibility. This solution can differentiate between requests that should result in an app load versus a legitimate 404. However, it requires a broader understanding of NGINX configuration syntax and directives.

Summary

In summary, configuring NGINX to play nicely with React Router requires a few targeted tweaks to your setup. By ensuring that all paths lead back to index.html, you honor the routing rules defined within your SPA. As with any powerful tool, slap on those best practice gloves – these adjustments are potent, yet when mishandled, may yield undesirable performance woes or expose gaps in server security.

Next Article: NGINX error: No ‘ssl_certificate’ is defined in server listening on SSL port

Previous Article: NGINX Error: The plain HTTP request was sent to HTTPS port

Series: NGINX Tutorials

DevOps

You May Also Like

  • How to reset Ubuntu to factory settings (4 approaches)
  • Making GET requests with cURL: A practical guide (with examples)
  • Git: What is .DS_Store and should you ignore it?
  • NGINX underscores_in_headers: Explained with examples
  • How to use Jenkins CI with private GitHub repositories
  • Terraform: Understanding State and State Files (with Examples)
  • SHA1, SHA256, and SHA512 in Terraform: A Practical Guide
  • CSRF Protection in Jenkins: An In-depth Guide (with examples)
  • Terraform: How to Merge 2 Maps
  • Terraform: How to extract filename/extension from a path
  • JSON encoding/decoding in Terraform: Explained with examples
  • Sorting Lists in Terraform: A Practical Guide
  • Terraform: How to trigger a Lambda function on resource creation
  • How to use Terraform templates
  • Understanding terraform_remote_state data source: Explained with examples
  • Jenkins Authorization: A Practical Guide (with examples)
  • Solving Jenkins Pipeline NotSerializableException: groovy.json.internal.LazyMap
  • Understanding Artifacts in Jenkins: A Practical Guide (with examples)
  • Using Jenkins with AWS EC2 and S3: A Practical Guide