I am using Apache 2.2 to host my reactjs app ... in my App.js I have this code
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router,
Route,
Link,
Switch,
Redirect
} from 'react-router-dom';
import Home from './components/Home';
import Cat from './components/Cat';
const NoMatch = ({ location }) => (
<div>
<h3>No match for <code>{location.pathname}</code> can be found.</h3>
</div>
)
class App extends Component {
render()
return (
<Router>
<div>
<Navbar />
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/home" component={Home} />
<Route exact path="/cat" component={Cat} />
<Route component={NoMatch} />
</Switch>
</div>
</Router>
);
}
}
export default App;
I then use npm run build and everything in my build folder is moved to my DocumentRoot folder /var/www/html/home
In this /var/www/html/home i also have a .htaccess file and in that I have
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ ./index.html
When i go to /Home it is fine and when i hit refresh it is ok. but then i click a link and it brings me to /cat and again it is fine but then when i refresh it shows
Not Found The requested URL /cat was not found on this server.
Has anyone come across this issue ? I see so much online about the .htaccess file fixing the issue but it has not worked for me at all
An alternative way to handle 404 page not found in React router is to redirect the user to a different page when they try to go to a page that doesn't exist. Copied! In the example, instead of rendering a PageNotFound component, we redirect the user to / if they go to a route that doesn't exist. Copied!
To install React Router, all you have to do is run npm install react-router-dom@6 in your project terminal and then wait for the installation to complete. If you are using yarn then use this command: yarn add react-router-dom@6 .
We can start looking at the React HashRouter and its applications. A Router that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL. (
I had the same problem on the server, run npm run build, create a folder with the compiled project, inside build create the .htaccess file with:
RewriteEngine On
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -f [OR]
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} -d
RewriteRule ^ - [L]
RewriteRule ^ ./index.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With