Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basename not working properly

Tags:

react-router

I'm attempting to use a basename with react-router as documented on the react-router docs. This is due to base href being deprecated.

Here is what I have now:

import { Route, Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
import { render } from 'react-dom';

var history = useRouterHistory(createHistory)({
  basename: '/subdirectory'
});

render(
  <Router history={history}>
    <Route path='/' component={App}>
      <Route path='next' component={Next} />
    </Route>
  </Router>,
  document.getElementById('root')
);

When I go to http://the-url.com/subdirectory the page loads as expected (rendering the App component). However, when going to http://the-url.com/subdirectory/next, I get a 404 error. My nginx config is:

location /subdirectory {
  alias /path/to/index.html;
  index index.html;
  try_files $uri $uri/ /path/to/index.html;
}
like image 352
aaron Avatar asked Jun 17 '16 17:06

aaron


People also ask

What is basename BrowserRouter?

The basename prop is used to provide a base URL path for all the locations in the application. For example, if you want to render your application at the /admin path instead of rendering at the root path / , then specify the basename prop in <BrowserRouter> : <BrowserRouter basename="/admin"> <App /></BrowerRouter>

What is the difference between BrowserRouter and router?

The main difference between the two is the way they store the URL and communicate with your web server. A <BrowserRouter> uses regular URL paths.

What is HashRouter in react router?

We can start looking at the React HashRouter and its applications. A Router that uses the hash portion of the URL (i.e. window.location.hash) to keep your UI in sync with the URL. (

How do I set a default route in react?

Use the Navigate element to set a default route with redirect in React Router, e.g. <Route path="/" element={<Navigate to="/dashboard" />} /> . The Navigate element changes the current location when it is rendered. Copied!


1 Answers

Here is how I managed to get it to work

Set Router basename to your subdirectory like this

<Router basename="/subdirectory">

If you used create-react-app and are building using npm run build you need to set homepage in package.json for the paths to be correct in the production build

homepage: "{http://www.the-url.com/subdirectory}"

For the nginx config, let's assume your index.html is under /path/to/subdirectory/index.html. Then the following should work

location /subdirectory {
    root /path/to;
    try_files $uri $uri/ /subdirectory/index.html;
}
like image 125
Per Thoresson Avatar answered Sep 23 '22 00:09

Per Thoresson