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

Angular网站部署Nginx后直接访问URL出现404错误如何解决?

解决Angular部署Nginx后直接访问路由404且隐藏URL中#号的问题

要解决这个问题,需要从Angular路由配置和Nginx服务器配置两方面入手:

1. 启用Angular的HTML5路由模式

Angular默认使用Hash模式(带#号的URL),要隐藏#号需切换到HTML5模式:

  • 打开项目中的app-routing.module.ts文件,做如下配置:
    import { NgModule } from '@angular/core';
    import { Routes, RouterModule, LocationStrategy, PathLocationStrategy } from '@angular/router';
    // 导入你的组件
    import { LoginComponent } from './login/login.component';
    
    const routes: Routes = [
      { path: 'login', component: LoginComponent },
      // 其他路由配置...
      { path: '**', redirectTo: '' } // 兜底路由,处理未匹配的路径
    ];
    
    @NgModule({
      imports: [RouterModule.forRoot(routes)],
      exports: [RouterModule],
      // 配置使用HTML5模式
      providers: [{ provide: LocationStrategy, useClass: PathLocationStrategy }]
    })
    export class AppRoutingModule { }
    
  • 也可以直接在forRoot方法中显式关闭Hash模式:
    RouterModule.forRoot(routes, { useHash: false })
    

2. 修改Nginx配置,将所有路由请求指向index.html

因为Angular是单页应用,所有路由对应的文件在服务器上实际不存在,需要Nginx把所有请求转发到index.html,由Angular路由系统处理:

  • 找到你的Nginx站点配置文件(通常位于/etc/nginx/sites-available/或直接在nginx.conf中)
  • 修改server块内容,添加try_files指令:
    server {
      listen 80;
      server_name example.com;
    
      # 替换为你的Angular打包后dist目录的绝对路径
      root /var/www/angular-project/dist;
      index index.html;
    
      location / {
        # 核心配置:优先找对应文件,找不到就返回index.html
        try_files $uri $uri/ /index.html;
      }
    
      # 如果有API代理需求,可在此添加相关配置
      # location /api {
      #   proxy_pass http://your-api-server-address;
      # }
    }
    

3. 验证配置并重启Nginx

  • 执行nginx -t检查配置是否合法
  • 检查通过后,执行systemctl restart nginx(或service nginx restart)重启Nginx服务

完成以上配置后,直接访问http://example.com/login这类URL就不会出现404错误,同时URL中也不会显示#号。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:40:06