Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refresh react app, 404 error. React router issue

I'm using react-boilerplate (https://github.com/react-boilerplate/react-boilerplate) My app works perfectly on localhost, but after deploying on the server in a SUBDIRECTORY (important! not in the root!) application works until refreshing...If i try to refresh when app is in others route (/something/here), I received 404 error page not found.

I searched a lot about this issue, I figured out what is the problem and solutions but I can't fix that...you can see here issue explanation: https://tylermcginnis.com/react-router-cannot-get-url-refresh/

I'm using React Router 4. Maybe I need to use historyApiFallback: true but Idk how to use that with react boilerplate which has a lot of webpack config files (not only one..). Any help?

like image 557
razer90 Avatar asked May 14 '26 21:05

razer90


1 Answers

I also had this problem before. Perfectly fine on localhost, but refreshing on non-root routes or directly typing non-root URL's always gave me 404. It came to conclusion that it cannot find non-root directories on it's own as React only has index.html as its HTML document and needs some rewriting rules.

In my case, my host is using Apache and adding .htaccess to my web root directory with the following content worked:

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

For nginx, you need to of course modify the nginx configuration. I found one answer here and it looks much simpler than the Apache one: React-router and nginx

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

Basically you need to tell the web server to forward ALL requests to your React's index.html, and therefore letting react-router handle the routing.

Other solution is to use HashRouter, but will result in some ugly URL.

like image 158
ionizer Avatar answered May 18 '26 07:05

ionizer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!