'React application on production - links don't work when requested directly, they work only when accessed by react router
I have deployed an application on a ubuntu server.
I ran npm run build
, and copied all the content of build inside /var/www/html
The file /etc/nginx/sites-available/default looks like that (default value):
server {
listen 80 default_server;
listen [::]:80 default_server;
root /var/www/html;
index index.html;
server_name _;
location / {
try_files $uri $uri/ =404;
}
}
When trying to access 111.111.11.11/contact-us directly with the browser, I get a 404. What am I missing? why doesn't the react app handle that request?
Here is some code:
History.js:
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
App.js:
import { Router, Route, Switch } from "react-router-dom";
render() {
return (
<div className="page">
<Router history={history}>
<Header />
<Switch>
<Route path="/combination/:uniqueUrl" exact component={CombinationPage} />
<Route path="/" exact component={MainContent} />
<Route path="/contact-us" exact component={ContactUs} />
<Route path="*" exact component={PageNotFound} />
</Switch>
</Router>
</div>
)
}
Important update: If I add a /#/, it's working and I can access the page. For example http://111.111.11.11/#/contact-us.
Important information: Locally it's working correctly when using "npm run start"
the problem is when it's on the ubuntu server, after running npm run build
.
Solution 1:[1]
Yes, i know, I am replying a long time later, but today I had the same error, I solved it by editing the nginx config file
location / {
try_files $uri $uri/ /index.html =404;
}
I hope that it would be useful to someone
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Pablo Venegas E |