Frosty619 Frosty619 - 27 days ago 7
React JSX Question

Cannot GET 404 err when refreshing pages if url has multiple subpaths

My frontend is React/Redux with a backend API in PHP. I am using Webpack with historyApiFallback enabled:

devServer: {
historyApiFallback: true,
contentBase: './',
hot: true
}


I am using
redux-persist
to make refreshing work. I am able to refresh the page if the url is :
localhost:8000/summary
or any url which has only one path, but if the url has multiple subpaths, like so:
localhost:8000/summary/customers
, I get the Cannot GET 404 err.

My routes are defined like so:

export default (
<Route path="/" component={App}>
<Route path ="summary" component={SummaryItems} />
<Route path ="summary/customers" component={AllCustomersSummary} />
//more routes
</Route>
);


I looked at other answers but the suggested solution(enabling
historyApiFallback
) is not working in this particular case.

Answer

Here is how I solved the problem:

1.Create an .htaccess file in the root directory and add the following:

    RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

Note that index.html is the homepage file(the file containing your react app), for me it was home.php. To my understanding(please correct me if I am wrong) the above solves the problem because when you refresh the page, a request is sent to the server with the url, which does not exist on the server, so the server sends back the homepage which contains your react app.

Note: This solution does not work on localhost.

Comments