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;
}
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>
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.
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. (
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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With