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

Angular应用部署后刷新页面出现404错误求解决方案

解决Angular部署后刷新页面404的问题

Angular作为单页应用(SPA),本地运行时依赖DevServer处理前端路由,但部署到服务器后,刷新页面时服务器会尝试寻找对应路径的物理文件,找不到就返回404。以下是几种可行的解决方案:

1. 配置服务器重写规则

核心思路是让服务器把所有非静态资源的请求转发到index.html,由Angular前端路由处理:

  • Nginx:修改站点配置文件,在location /块中添加:
location / {
  try_files $uri $uri/ /index.html;
}
  • Apache:在项目根目录创建.htaccess文件,写入:
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>
  • IIS:在项目根目录的web.config中添加重写规则:
<system.webServer>
  <rewrite>
    <rules>
      <rule name="Angular Routes" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/index.html" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

2. 切换为Hash模式路由

这种方式会在路由路径前添加#,服务器只会解析#之前的部分,不会去寻找对应路径的文件:
在app-routing.module.ts中修改路由配置,两种方式二选一即可:
方式一:配置useHash参数

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  // 你的路由定义
];

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

方式二:注入HashLocationStrategy

import { NgModule } from '@angular/core';
import { Routes, RouterModule, HashLocationStrategy, LocationStrategy } from '@angular/router';

const routes: Routes = [
  // 你的路由定义
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]
})
export class AppRoutingModule { }

3. 静态托管服务专属配置

如果部署到Netlify、Vercel这类静态托管平台,可通过配置文件实现路由转发:

  • Netlify:在项目根目录创建_redirects文件,内容为:
/*    /index.html   200
  • Vercel:在项目根目录创建vercel.json文件,内容为:
{
  "rewrites": [
    { "source": "/(.*)", "destination": "/index.html" }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:30:12