I have my website hosted on a subdirectory, as an example, http://mywebsite/admin, where /admin is the subdirectory
I have my react app (create-react-app production build) uploaded into the /admin subdirectory. I am also using react-router v4 BrowserRouter to have some simple client-side routing performed. Below are some relevant snippets on my react-app:
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import { BrowserRouter } from 'react-router-dom';
import './css/custom.css';
ReactDOM.render(<BrowserRouter basename="/admin"><App /></BrowserRouter>, document.getElementById("root"));
inside App.jsx render function
<Route
path='/students'
render={(props) =>
<Students
{...props}
/>
}
/>
<Route
path='/teachers'
render={(props) =>
<Teachers
{...props}
/>
}
/>
All is well and working when navigating the site including the nested urls which are mainly, as you have seen on the snippets, /admin/students & /admin/teachers.
The main issue: when I am on the /admin/teachers route and I refresh the page, the page does not load anything. Refreshing works when I am on /admin route only. But not when it is /admin/teachers nor /admin/students.
This is not the first time I have built an SPA using react-router v4 hosted on Apache server. I have reused the .htaccess I have on my previous project. This .htaccess also resides at the /admin subdirectory. Below is the .htaccess:
.htaccess
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.html?path=$1 [NC,L,QSA]
This routes all requests to the index.html built by the create-react-app production build. However, upon my investigations, this type of configuration only works on a project that is not on a subdirectory and is not using nested URLs.
Note, that I have 2 .htaccess now. One on root and another one at the /admin subdirectory. Both contain the same .htaccess codes. The reason for this is, I have another SPA running at the root directory.
What am I missing?
How to Properly Configure Apache on a SPA React App that Resides on a Subdirectory that uses Nested URLs built from React Router?