How To: Setup React client-side routing with Apache and sub-directories

Before I get started (or yelled at) I have to point out that this topic is already covered in the Create React App docs. This post is meant to cover a very specific use case – serving a react app that uses client-side routing (like react-router) on an Apache driven shared host from within a sub-directory on the server. I’m also assuming you’ve bootstrapped your project with the Create React App tool, since we’ll be relying on it’s build script.

To begin we’ll need to create a .htaccess file in the public folder and add the following rule:

FallbackResource ./index.html

This file will get copied into build when we run npm run build. The rule is fairly self explanatory – we’re defining a fallback resource that handles all requests. The next step is to open package.json and add:

"homepage": "."

This makes sure that all asset paths are relative to index.html. Finally you’ll want to run npm run build to package your app for deployment. Once that’s done you can upload the contents of the build folder to a sub-directory your shared host, e.g. /myreactapp. If everything was done correctly you should now be able to see your app on whatever domain you have mapped to your sub-directory.

Tutorials , ,