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

Angular 8部署后页面刷新报404,常用修复方案均无法解决

排查及解决方案

1. 优先排查HashLocationStrategy未生效的问题

Hash模式是无需后端配合即可解决刷新404的方案,配置未生效大概率是操作疏漏:

  • 确认你代码中的provider配置已经正确放入app.module.ts的providers数组内,完整配置参考:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HashLocationStrategy, LocationStrategy } from "@angular/common";
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule],
  // 配置必须放在providers数组内才会生效
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • 配置修改完成后必须重新执行ng build --prod打包,并且将新的dist目录下的所有文件完全覆盖服务器上的旧打包文件,未重新打包的情况下修改代码不会生效。
  • 配置生效后站点地址会自动携带#标识,例如http://你的域名/#/home,如果访问地址没有#说明配置未生效,先解决该问题即可直接解决404问题。

2. 若需要使用无#的PathLocationStrategy,按服务器类型排查配置

若使用Apache服务器(对应.htaccess配置)

  • 先确认Apache已经开启mod_rewrite模块,可通过phpinfo页面查看模块是否加载,未开启的情况下重写规则完全不生效。
  • 确认Apache虚拟主机配置中,对应站点的<Directory>段设置了AllowOverride All,否则.htaccess文件会被服务器直接忽略不执行。
  • 确认.htaccess文件放在Angular打包产物的根目录(和index.html同目录),文件权限设置为服务器可读取。
  • 若项目部署在站点子目录,例如访问地址为http://域名/myapp/,需要将.htaccess的最后一条重写规则改为RewriteRule ^ myapp/index.html [L],同时打包时添加base-href参数:ng build --prod --base-href /myapp/。

若使用IIS服务器(对应web.config配置)

  • 确认IIS已经安装URL重写模块,未安装的情况下web.config内的rewrite规则不会生效。
  • 子目录部署的情况下,需要将配置中action的url属性改为/myapp/,同时打包时添加--base-href /myapp/参数。
  • 确认web.config放在index.html同目录,IIS站点有读取该配置文件的权限。

若使用Nginx服务器

.htaccess和web.config配置对Nginx完全不生效,需要在Nginx站点配置中添加如下规则:

# 根目录部署
location / {
  try_files $uri $uri/ /index.html;
}

# 子目录部署示例
location /myapp/ {
  try_files $uri $uri/ /myapp/index.html;
}

3. 其他排查点

  • 确认后端接口路由和Angular前端路由没有重名冲突,比如后端统一用/api/作为接口前缀,前端路由不要设置/api/开头的路径,避免路由被后端拦截导致404。
  • 检查服务器安全组、WAF等规则是否拦截了非常规路径的访问。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:39:04