React Router on PHP Hosting
As you already know, after building, a React project is just regular static content that can be uploaded to any hosting, and it will work there immediately.
However, there is a problem with React Router. The thing is, the Router during operation changes the page URL in the browser. At the same time, the page does not actually reload, only the URL changes using JavaScript.
The Router will work on a site uploaded to hosting.
But, if you are on any page of the site, except the main one,
and reload it, you will get a 404
error.
And this is logical, because the browser will
look for a file at the specified URL,
as static sites usually work.
And in our application, such a page
will not exist, since we are only simulating
them, while in reality all our
application runs on index.html.
To solve the problem, you need to make it so that
all URLs that do not lead to actually
existing files are redirected
to index.html. This is done
by means of the web server running
on the hosting.
Virtual hostings run on PHP.
Typically, Apache is used as the server.
It provides a special file .htaccess,
which can be used to set up
redirection.
To do this, in the root of your site
you need to place a file .htaccess
with the following content:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]
Create a project with React Router.
Upload it to the hosting. Make sure that routing does not work by default.
Fix the problem using the
.htaccess file.