June 25, 2021

Hosting frontend apps with webservers

Here’s a short guide to host your frontend app with a webserver – like React App or any other static web app which utilies browser’s History API.

History API is a way for the frontend app to control which page is displayed on the browser. This allows creating frontend apps that look like normal web pages with their unique URLs for different parts of the app.

In order for the reload (F5) to work for any of these frontend-side locations, you need to configure your webserver to serve your frontend bundle HTML page (index.html) for any of these paths which do not exist on the server.

Apache

Apache is probably most common HTTP server for shared hosting environments.

It’s simple and usually doesn’t need you to change – or know about – HTTP server configurations.

Just create a .htaccess file in your docroot where your compiled web app is located:

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

This configures Rewrite engine to serve any request that isn’t a real file using the index.html file.

It also disables MultiViews, which is Apache’s feature to use pattern matching to choose from multiple files.

If this doesn’t work, you may need to contact your server administrator and ask to make sure the Rewrite module is loaded and/or you have enough permissions to use .htaccess.

One way to give enough permissions is to give the docroot access to override everything using AllowOverride All. However, this requires administrator level access to the server.

To enable Rewrite module on a Debian based system, just run a2enmod rewrite. Other systems may need manual configuration.

Nginx

With Nginx you will need to edit actual HTTP server configurations.

Configuring Nginx probably requires administrator level access to your server. (Unless you’re using containers.)

Your configuration might look like this:

server {
        listen 80;
        listen [::]:80;
        root /var/www/html;
        index index.html;
        server_name example.com;

        location / {
                try_files $uri $uri/ =404;
        }
}

The part you want to change is the location / block:

location / {
        try_files $uri $uri/ =404;
}

Your original block may have had different lines, since there’s quite a lot of ways to configure Nginx.

The line you want to change is:

try_files $uri /index.html;

This will tell Nginx to handle non-existing files using /index.html and your frontend bundle will take care of the rest.

In the end you will need to remember to reload Nginx configurations: