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

Nginx配置问题:Angular特定路由访问出现404 Not Found错误

问题分析与解决

问题根源

  • 核心原因是Nginx配置问题:你当前location /块的try_files指令末尾添加了=404,主站请求能正常命中index.html,但处理/ex/test这类前端路由时,Nginx会在尝试完$uri和$uri/后错误触发=404返回,而非转发到index.html让Angular的前端路由系统处理。你为/gifs单独配置的try_files没有加=404,所以该路由能正常工作,这也佐证了配置的问题。
  • 辅助排查点:需确认Angular项目开启了HTML5路由模式(非Hash模式),index.html里的<base href="/">配置正确,且/ex/test对应的路由已在Angular路由模块中定义。

解决步骤

1. 修正Nginx配置

修改location /块的try_files指令,移除末尾的=404:

# Serve Angular application
location / {
    try_files $uri $uri/ /index.html;
}

同时可以删除单独的location /gifs块,修正后的location /已能覆盖所有前端路由请求,无需逐个配置。

2. 验证Angular项目配置(若修正Nginx后仍有问题)

  • 检查app-routing.module.ts,确保启用HTML5模式:
    @NgModule({
      imports: [RouterModule.forRoot(routes, { useHash: false })],
      exports: [RouterModule]
    })
    
  • 确认index.html中的<base href="/">设置正确。
  • 确保/ex/test对应的路由规则已在routes数组中定义。

3. 重启Nginx使配置生效

执行命令:

sudo nginx -s reload

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 07:33:21