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 React code base and NGINX config.

Version

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 so that it adds the web path to your build output. You have the actual domain URL and the subpath you wish your page to be on.

{
    "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> for linking your internal pages. 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 changing them 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 with npm 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 your 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 Software Engineering, Data Science, and Machine Learning.

Background

Full-stack engineer who builds web and mobile apps. Now, exploring Machine Learning and Data Engineering.

Writing unmaintainable code since 2010.

Skill/languages

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

Work

Engineering Manager

Location

Kuala Lumpur, Malaysia

Open Source
Support

Turn coffee into coding guides. Buy me coffee