← coderrocketfuel.com

Fix 404 Error When Using React-Router-Dom & Nginx

You've got a React application built and deployed to production, but react-router-dom isn't playing nicely with Nginx and you are seeing 404 pages when loading your routes directly.

The most likely issue is that you're not telling Nginx to forward other requests to the /index.html of your application, which makes it so your other pages can't be loaded directly and display a 404 error.

To fix this, you'll need to make a small change to your Nginx configuration files.

Open the Nginx sites-available configuration file for your website (replace default with the filename for your website):

sudo nano /etc/nginx/sites-available/default

And change the location section to the following:

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

Everything else in the file can be kept the same.

Save and close the file when you are finished.

Next, test to make sure that there are no syntax errors in any of your Nginx files:

sudo nginx -t

If no problems were found, restart Nginx to enable your changes:

sudo systemctl restart nginx

Go to your website and view your changes. You should be able to reload each of your URL routes and the 404 error issues you were experiencing should be gone.