Basename 无法正常工作 [英] Basename not working properly
问题描述
我正在尝试将基本名称与 react-router 一起使用,如文档所述 关于 react-router 文档.这是因为 base href 已被弃用.
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.
这是我现在所拥有的:
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')
);
当我转到 http://the-url.com/subdirectory
时,页面按预期加载(呈现 App
组件).但是,当转到 http://the-url.com/subdirectory/next
时,出现 404 错误.我的 nginx 配置是:
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;
}
推荐答案
这是我设法让它工作的方法
像这样将路由器基名设置为您的子目录
Here is how I managed to get it to work
Set Router basename to your subdirectory like this
如果您使用 create-react-app 并使用 npm run build 进行构建,则需要在 package.json 中设置主页,以使生产构建中的路径正确
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
主页:{http://www.the-url.com/subdirectory}"
对于 nginx 配置,假设您的 index.html 位于 /path/to/subdirectory/index.html
下.那么以下应该工作
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;
}
这篇关于Basename 无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!