React Routing with Apache

I've been working on a single page app in React for the past several months, currently in alpha testing. It uses React Router to handle its routing, and is bootstrapped with Create React App, which makes getting started as easy as they tell you. One thing that came up in testing deals with the way routing works when deployed to a web server running Apache (or nginx, but this project is on Apache) — once you've loaded up React, the app is navigable just fine, but if you're anywhere but the home page (e.g. /pages/124) and refresh the browser, you'll get a 404 error.

Running the development server in Create React App means not having to see this, so it can be easy to miss at first. One way to work around this, and a good one for SEO, is to use a server-side renderer so every page is rendered into HTML on the server, with React taking over in the browser from there. This project will never be available to the public internet, so SEO doesn't particularly matter, and certainly while we're in development, I just wanted the thing to work when you refreshed.

It turns out that you can do the same thing WordPress, Drupal, and many other PHP-based CMSes do to handle routing. Something like this in your .htaccess file will do the trick, assuming your entry point is index.html (as it is with Create React App).

Options -MultiViews

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L,NC,QSA]
</IfModule>

This will take all URLs that aren't actual files or directories and send them to your index.html file, where React Router picks them up.

Categories: 
Tags: 
Comments are closed on this post to keep spammers at bay. If you want to chime in, please email or send a tweet.