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

Docker中Nginx代理Angular5应用资源加载404的解决方法

解决Angular应用在Nginx反向代理子路径下的资源404问题

你遇到的问题非常典型——Angular的base href决定了所有静态资源的加载基准路径,默认的/在反向代理到子路径(比如/dmr/)时,会导致资源请求直接指向根域名,从而触发404错误。除了重新构建时指定--base-href,这里有几个无需重新构建的替代方案:

方案1:Nginx动态替换index.html中的base href(推荐)

利用Nginx的sub_filter模块,在返回index.html时自动替换其中的base href值,无需修改Angular项目代码或重新构建。

修改你的Nginx配置:

location /dmr/ {
    # 代理到你的Angular容器地址(根据实际情况调整)
    proxy_pass http://your-angular-service:4200/;
    proxy_set_header Host $host;
    
    # 替换index.html中的base href值
    sub_filter '<base href="/">' '<base href="/dmr/">';
    # 只执行一次替换,避免误修改其他内容
    sub_filter_once on;
}

这个方案精准解决了资源路径问题,对Angular应用本身无侵入,适合需要快速调整部署路径的场景。

方案2:Nginx重写资源请求路径

如果不想修改base href,可以通过Nginx的rewrite规则,把所有指向根路径的资源请求重定向到/dmr/路径下。

配置示例:

# 处理反向代理的主路径
location /dmr/ {
    proxy_pass http://your-angular-service:4200/;
    proxy_set_header Host $host;
}

# 拦截静态资源请求,重写到/dmr/路径下
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf)$ {
    rewrite ^/(.*)$ /dmr/$1 last;
    proxy_pass http://your-angular-service:4200;
}

注意:如果服务器上还有其他根路径的应用,这个规则可能会干扰它们的资源请求,更适合单应用部署的场景。

方案3:Angular代码中动态设置APP_BASE_HREF

如果你希望一次构建后能适配任意子路径部署,可以在Angular应用中通过APP_BASE_HREF注入动态获取当前路径。

修改app.module.ts:

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF } from '@angular/common';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    // 根据当前URL的路径段动态设置base href
    { 
      provide: APP_BASE_HREF, 
      useValue: window.location.pathname.split('/')[1] ? `/${window.location.pathname.split('/')[1]}/` : '/' 
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这个方案需要你重新构建一次应用,但之后不管部署到哪个子路径(比如/dmr/、/app/),Angular都会自动适配资源路径,无需再次构建。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:16:13