Angular 11直接访问非根路由被重定向到首页如何解决?
问题原因
Angular 默认使用 HTML5 路由模式(PathLocationStrategy),路由跳转通过前端 history API 实现无需刷新页面,但直接在地址栏输入非根路径时,浏览器会先向服务器发起该路径的请求,若服务器没有配置将所有路由请求重定向到应用入口 index.html,就会出现跳转回根路由或404的问题。
解决方案
1. 修正基础路由配置
首先确认路由配置添加了正确的空路径匹配规则,避免空路径错误拦截所有路由:
const routes : Routes = [ // 新增 pathMatch: 'full',仅当路径完全为空时匹配首页 { path: '', component: HomeComponent, pathMatch: 'full' }, { path: 'product/:id', component: ProductComponent }, // 可选配置:添加404路由捕获不存在的访问路径 { path: '**', component: NotFoundComponent } ]; // 检查路由模块注册逻辑是否正确 @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
2. 本地开发环境配置
使用 ng serve 启动的本地开发服务默认已支持HTML5路由模式,若仍出现重定向问题,可启动时添加指定根路径参数:
ng serve --serve-path / --open
3. 生产环境服务端配置(核心)
部署上线时需要配置服务端,将所有路由请求都重定向到应用的入口 index.html,不同服务端的配置如下:
- Nginx 配置:在站点配置的server块中添加规则
location / { try_files $uri $uri/ /index.html; }
- Apache 配置:在项目根目录新建
.htaccess文件添加规则
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
- Node.js Express 配置:在服务路由逻辑末尾添加兜底规则
app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'dist/index.html')); });
备选方案:切换Hash路由模式
如果无法修改服务端配置,可以切换为Hash路由模式,该模式下路由会携带#前缀,所有请求默认访问根路径的index.html,无需服务端额外配置:
@NgModule({ // 新增 useHash: true 开启Hash路由模式 imports: [RouterModule.forRoot(routes, { useHash: true })], exports: [RouterModule] }) export class AppRoutingModule { }
配置后访问路径会变为 https://localhost:4200/#/product/14,直接输入该地址即可正常访问对应页面。
内容的提问来源于stack exchange,提问作者Alin Popa
相关产品推荐
相关产品推荐

