The issue you're encountering likely arises from the fact that React applications using React Router rely on client-side routing, which means that the server does not automatically understand how to handle routes that aren't explicitly defined in your server configuration.
When you navigate directly to a URL like test.com/projects, the server tries to find a file at that path, and since it doesn't exist, you get a "File not found" error. Here’s how you can resolve this:
1. Configure Your Server for React Router
You need to configure your server to serve the index.html file whenever a request does not match a file. How you do this depends on the server you are using.
For Nginx
If you are using Nginx, you can set up your server block to redirect all requests to index.html:
server {
listen 80;
server_name test.com;
location / {
root /path/to/your/build/folder; # Change this to your actual path
try_files $uri /index.html;
}
# Optional: Add gzip compression
gzip on;
gzip_types text/css application/javascript;
}
For Apache
In an Apache server, you'll want to use a .htaccess file in your build folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
For Express.js (Node.js)
If you are using Express for your backend, you can add a catch-all route to send all requests to your index.html file:
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the React app
app.use(express.static(path.join(__dirname, 'build')));
// The "catchall" handler: for any request that doesn't
// match one above, send back index.html
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
2. Using HashRouter Instead of BrowserRouter
Alternatively, if you do not have control over the server configuration or prefer not to set it up for client-side routing, you can use HashRouter from react-router-dom instead of BrowserRouter. This approach works since it uses the URL hash for routing, which doesn’t require server configuration:
import { HashRouter as Router } from 'react-router-dom';
function App() {
return (
<Router>
{/* Your routes here */}
</Router>
);
}
Conclusion
After making the appropriate changes based on your server type, try accessing test.com/projects again, and it should correctly serve your React application without the "File not found" error.