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

Angular项目window.open线上404问题:本地正常部署后报错

Angular部署后路由404问题解决办法

1. 确认路由模式配置

Angular默认使用PathLocationStrategy(HTML5模式),本地ng serve会自动处理路由重写,但部署到外部服务器后需要额外配置。如果尝试加#访问无效,大概率是项目未启用Hash模式:

  • 修改app-routing.module.ts,启用Hash模式:
    @NgModule({
      imports: [RouterModule.forRoot(routes, { useHash: true })],
      exports: [RouterModule]
    })
    export class AppRoutingModule { }
    
  • 重新构建部署后,路由会变为带#的格式,比如https://myWebserver.com/#/newWindow,此时直接访问或用window.open('/#/newWindow', "_blank")即可正常打开。

2. 服务器端配置(保留HTML5模式,不带#)

如果想继续使用无#的路由,需要配置服务器将所有路由请求转发到index.html(因为Angular是单页应用,所有路由逻辑由前端处理):

  • Nginx:在server配置块中添加重写规则
    location / {
      try_files $uri $uri/ /index.html;
    }
    
  • Apache:在项目根目录创建.htaccess文件,添加:
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.html$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.html [L]
    
  • 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>
    

3. 检查部署完整性

确认ng build(生产环境用ng build --prod)生成的dist文件夹内所有文件都完整部署到服务器的根目录(或你指定的部署目录),尤其不能遗漏index.html。

4. 服务器端调试技巧

  • 查看服务器日志:比如Nginx的access.log和error.log、Apache的error.log,日志会记录404请求的具体路径、响应状态等信息,帮你定位问题。
  • 用命令行测试:在服务器上执行curl -v https://myWebserver.com/newWindow,查看返回的响应头和内容,确认是服务器返回的404,还是其他异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:00:59