You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Apache部署Angular 15时通配路由自定义404页面失效问题解决

解决Angular 15部署到Apache2后自定义404页面不显示的问题

问题根源是Angular作为单页应用(SPA),所有路由均为前端路由,Apache默认会将不存在的路径视为服务器端资源请求,直接返回自身的404页面,而非交由Angular路由处理。通过配置.htaccess可解决该问题,步骤如下:

1. 启用Apache Rewrite模块

首先确保Apache的rewrite模块已启用,执行以下命令:

sudo a2enmod rewrite
sudo systemctl restart apache2

2. 创建/配置.htaccess文件

在Angular构建后的静态文件根目录(即Apache站点的根目录,通常为dist/你的项目名)下创建或修改.htaccess文件,添加以下内容:

<IfModule mod_rewrite.c>
  RewriteEngine On
  # 若项目部署在子目录(如http://example.com/my-app/),将此处改为 /my-app/
  RewriteBase /
  # 直接放行index.html请求
  RewriteRule ^index\.html$ - [L]
  # 若请求的文件或目录不存在,转发到index.html交由Angular路由处理
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

3. 确保Apache允许.htaccess生效

检查你的Apache站点配置文件(通常位于/etc/apache2/sites-available/你的站点.conf),在对应的Directory块中添加AllowOverride All,示例如下:

<Directory /var/www/你的项目根目录>
  AllowOverride All
  Require all granted
</Directory>

修改后重启Apache:

sudo systemctl restart apache2

4. 验证Angular路由配置

确认你的app-routing.module.ts中正确配置了通配路由,且该路由放在所有路由的最后(避免覆盖其他路由):

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { NotFoundComponent } from './not-found/not-found.component';
// 导入其他业务组件

const routes: Routes = [
  { path: '', component: HomeComponent },
  // 其他路由配置
  { path: '**', component: NotFoundComponent } // 通配路由必须放在最后
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

完成以上步骤后,重新部署静态文件到Apache服务器,访问不存在的路径时就会显示你的自定义404页面,而非Apache默认的404页面。

内容的提问来源于stack exchange,提问作者Smith

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 01:57:28