如何将create-react-app部署到cPanel子目录并解决子路由404问题
遗漏的必要配置如下
1. 给BrowserRouter添加basename属性
BrowserRouter默认基于站点根目录匹配路由,部署在子目录时需要显式指定basename参数为你的子目录路径,同时调整Route的path前缀避免重复拼接:
<BrowserRouter basename="/start" > <TopBar/> <Switch> <Route exact path="/" component={start}/> <Route path="/page1" component={page1}/> <Route path="/page2" component={page2}/> </Switch> </BrowserRouter>
2. 在子目录下添加Apache重写规则
cPanel默认使用Apache作为web服务器,直接访问前端路由路径时,服务器会尝试查找对应物理文件,不存在就返回404。你需要在子目录(和build生成的index.html同级)下新建.htaccess文件,写入以下规则将所有子目录请求转发给React应用的index.html,由前端路由接管:
<IfModule mod_rewrite.c> RewriteEngine On RewriteBase /start/ RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /start/index.html [L] </IfModule>
完成以上两项配置后重新打包上传即可解决子路径404问题。
内容的提问来源于stack exchange,提问作者Dy1012
相关产品推荐
相关产品推荐

