Angular 16生产环境刷新页面出现404错误求助
Angular 16生产环境刷新页面404问题解决办法
Angular属于单页应用(SPA),前端路由由Angular Router负责管理。本地开发时ng serve内置的服务器已经自动处理了路由 fallback逻辑,但生产环境部署的服务器默认会把每个URL当作静态文件路径去查找,找不到对应文件就返回404错误。
方案一:配置服务器路由 fallback(推荐)
根据你使用的服务器类型,添加对应的配置,让所有非静态资源的请求都指向项目根目录的index.html:
Nginx
修改Nginx的站点配置文件(如nginx.conf或站点专属配置),在location块中添加以下规则:
location / { try_files $uri $uri/ /index.html; }
保存配置后重启Nginx服务即可生效。
Apache
在项目部署的根目录下创建或修改.htaccess文件,写入以下内容:
RewriteEngine On RewriteBase / RewriteRule ^index\.html$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.html [L]
注意要确保Apache服务器已经开启了mod_rewrite模块。
IIS
在项目部署根目录创建web.config文件,添加以下配置:
<configuration> <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> </configuration>
方案二:启用Hash路由
如果无法修改服务器配置,可以切换Angular的路由模式为Hash模式。这种模式下URL会带上#前缀(比如https://app.abc.xyz/#/dashboard),服务器只会解析#之前的路径,不会触发404。
修改项目中的app-routing.module.ts文件:
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; const routes: Routes = [ // 你的现有路由配置 ]; @NgModule({ imports: [RouterModule.forRoot(routes, { useHash: true })], // 启用Hash路由 exports: [RouterModule] }) export class AppRoutingModule { }
修改完成后重新构建生产包(ng build --prod)并部署即可。
内容的提问来源于stack exchange,提问作者Tafsir Ahamed
相关产品推荐
相关产品推荐

