Answers to this and similar questions seem to neglect that, if using client-side routing (like React Router) there are some back-end changes that should be made when serving from a subdirectory.

There are several approaches to this. One is to use <HashRouter>; that approach is described well here, or in the React Router docs.

Another approach is to use <BrowserRouter> with Express. Here are the steps for that:

In your app:

    <BrowserRouter basename={process.env.PUBLIC_URL}>
        <Route path="/your_route">
        <Route exact path="/">

Then, in package.json, add:

homepage: ""

(Note that "." will not work, if you're using client-side routing.)

Then, in Express, try the connect-history-api-fallback package (which is recommended in the Vue Router docs).

const express = require('express');
const historyFallback = require('connect-history-api-fallback');

const app = express();

Without this, users will not be able to directly enter in the browser's url bar; they'll get a cannot GET error.

You can see an example of the above with Apache here.


in package.json

"homepage": ".",


If you are using react-router-dom, If you know your directory name you could set basename to "/directory-name" in the router


If you want to set the base name to be dynamic, use

(Note: This won't be useful if you are using sub routing)


Incase of sub routing, set a standard string to your routes


 let basename_path = null;
   var url = window.location.pathname.toLowerCase();
   if(url.indexOf("react") === -1){    // If string(react) not available
            basename_path = "/";
       var array = url.split("react");
       basename_path = array[0]+"react/";

 <Router basename={basename_path}>   
   <Route exact path="/react/home" component={home}/>
   <Route exact path="/react/contactus" component={contactus}/>
   <Route exact path="/react/aboutus" component={aboutus}/>               

Related Query

More Query from same tag