razer90
razer90

Reputation: 41

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?

Upvotes: 3

Views: 5208

Answers (2)

Yamir Ortega
Yamir Ortega

Reputation: 21

I had this issue former days ago, but with apache web server, so in my case the issue was the flag AllowOverwrite inside httpd.conf file that need to be changed from None to All.

Also you need to create a .htaccess file with the following values:

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

Also into your apache configuration you need to set the virtual directory where you will add your app and inside directory tag add the following lines:

<Directory "/your_virtual_path_directory">
   RewriteBase /
   Options Indexes FollowSymLinks
   AllowOverride All
   Require all granted
</Directory>

I hope I have helped

Upvotes: 0

ionizer
ionizer

Reputation: 1721

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.

Upvotes: 3

Related Questions