Apache Nginx Rewrite Configuration – React.js

Apache Nginx React.js

Single page applications (SPA) is a way to provide smooth browsing experience without loading the view every time to give you the feel as same as native mobile and desktop apps. It is made of a single html file along with JavaScripts bundles. All of the necessary code for the page is loaded only once and its content gets changed dynamically through JavaScript and this post will tell you about Apache Nginx rewrite configuration for React.js or any Single Page Application

Webservers like apache, nginx by default serves content from files where they are located. But in case of Single Page Application all the pages (url) are served by single html file and you need to rewrite (not redirect) all requests to index.html unless there is actually a file and this could be css or js files.

And here is the Apache Nginx rewrite configuration for React.js or any Single Page App on a custom path and on root path where all requests for files and folders that does not exists are redirected to index.html

Rewrite Example

Files | Directory Match (This should not be rewritten)
http://mydomainname.in/myreactapp/static/css/main.bb39b717.css

Unmatch – Actual page url (rewritten to index.html)
http://mydomainname.in/myreactapp/about/team

Apache

To host on root path just use <Location /> for http://mydomainname.in
To host on non-root path use <Location /myreactapp> for http://mydomainname.in/myreactapp

Nginx

To host on root path just use location / { for http://mydomainname.in
To host on non-root path use location /myreactapp { for http://mydomainname.in/myreactapp

IMPORTANT: If non-root path, don’t forgot to add “homepage”: “/myreactapp” in your app’s package.json

Apache Nginx rewrite configuration for React.js


If you are not able to view the above code see here.

The simple snippets used for Apache Nginx rewrite configuration for React.js or any single page application is explained below.

Apache Rewrite

This enables the rewrite engine:
RewriteEngine on

This checks for existing folders (-d) and files (-f):
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

And this does the actual rewriting to destination index.html:
RewriteRule . /myreactapp/index.html [L]

Note: Make sure that you’ve enabled rewrite module in apache. If not, enable by the below command and reload
sudo a2enmod rewrite
sudo service apache2 reload

Nginx Rewrite

try_files tries the literal path you specify in relation to the defined root directive and sets the internal file pointer.
try_files $uri $uri/ /myreactapp/index.html;
In our case, three urls are specified.

  1. $uri – 1st attempt Files Match
  2. $uri/ – 2nd attempt Directory Match
  3. /index.html or /myreactapp/index.html – Final attempt SPA Rewrite to index.html

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *