How to run your React application on a sub-path (e.g. /web)

This guide will show you how you can host and run your React application in a sub-path URL, changing it from www.example.com to www.example.com/web for all pages. It would show you the changes you need to make in your code and NGINX config.

Version

As for this guide, it is using React 17.0.X and react-router-dom 5.2.X. The implementation could be different for future versions.

React App

The following are the changes you need to make in your React App. This assumes you are using create-react-app project structure.

Step 1: Set homepage

In the package.json file, add the homepage property to so that it adds the web path to your build.

{
    "name": "my-app",
    "homepage": "https://www.example.com/web",
    "dependencies": {
        ...
    }
}

Step 2: Router history

Update the router to use history with custom options, adding the basename. In the index.js:

Create history

import { createBrowserHistory } from 'history';

const history = createBrowserHistory({ basename: '/web' });

Pass to router

// Change this
<Router />

// To this
<Router history={history} />

Step 3: Add to browser router

Add the basename to the BrowserRouter

<BrowserRouter basename={'/web'}>

Make sure you are using <Link to=""></Link> from react-router-dom instead of anchor <a href=""></a>. If you are using anchor links, you might have to take extra steps to add the subpath to all of them either using the env or to do it manually. The best is to change them all to use Link.

If you are already using Link, then you do not need to make any changes.

Step 5: Check

Now, you can run the app in development mode to check that the paths are automatically updated when you run again withnpm run dev on your localhost:3000. The paths should all automatically be updated.

Nginx

Add the following location in your NGINX config file for your app. Update the alias with you build path.

location ^~ /web {
        alias /var/www/my-app/build;
        try_files $uri $uri/ /web/index.html;
}

Then, restart nginx

sudo service nginx restart

Conclusion

That's it. You should now have your React static site running on a sub-path.

Wei-Ming Thor

I write guides on programming, mostly on how to be awesome at JavaScript.

Background

I am a full-stack engineer who build web and mobile apps.

Skill/languages

Best: JavaScript, Python, C
Others: Android, iOS, React Native, Ruby, PHP

Location

Kuala Lumpur, Malaysia