Programming

Set up Apache2 for a React site

A React website is a one-page site. The page never gets reloaded, all content is shown within the existing page. Don’t get fooled by the url in the location bar changing: the page changes the url, but the http-page remains the same. A problem that arises with such a site is the following. When you close your browser when you are in a particular page in the site, when you open your browser, it tries to load the page in the location bar. However, that is not the url that starts the React site, and what you get is a “404 Page Not Found”.

What you can do is setup your Apache web server to redirect all pages to the root page, the url ending with “.com” (or any top level domain) and nothing else. This is what you add in the virtualHost configuration in your Apache server:

RewriteEngine on
# Don't rewrite files or directories
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
# Rewrite everything else to index.html to allow html5 state links
RewriteRule ^ index.html [L]

The two lines with “RewriteCond” prevent redirection of site content, the last line redirects all pages to the entry page of the site (that is, to the index.html page). This way, when you shutdown your computer while browsing the site, when you open your browser again, it will show you the site, not a 404 error.

This solution comes from Stackoverflow.