Before using React as a universal Node application at my current job, there were several times where I created one off sites that I wanted to put up on my old server. (mostly for portfolio purposes)
Source of the problem
What I realized is that under that subdomain routing on server side render never really worked. This is because Apache doesn't recognize the routes that your React application defines as safe routes.
It looks for one of these files instead:
- index.html
- index.shtml
- index.php
- index.htm
- default.html
- page1.html
- index.pl
- index.cgi
- index.php
- home.html
If any of these files are found in a folder with a directory that matches your route in Apache, it will serve that file instead instead of consulting your React application.
However, with one .htaccess
file in your application's directory, you can fix all of this pretty easily.
Solution
After building/transpiling your React site, make sure to place your built JavaScript code as well as any HTML and CSS you have in your www
directory.
After that place an .htaccess
file with this code:
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]
You should be good to go! If you have any questions or anything to add, leave a comment below.