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

配置Nginx部署带模块联邦的Angular 15 NX单体仓库求助

解决方案

一、修正Nginx核心配置

问题核心是Nginx未正确将Shell的子路由请求转发到Shell的入口文件,反而返回了根目录的index.html。以下是适配你的部署结构的完整Nginx配置:

server {
    listen 80;
    server_name your-domain.com;

    root /usr/share/nginx/html;
    index index.html;

    # 捕获Shell的所有路由请求,交给Angular路由处理
    location /shell/ {
        try_files $uri $uri/ /shell/index.html;
    }

    # 直接返回Remote模块的静态资源,找不到则返回404
    location /remote1/ {
        try_files $uri $uri/ =404;
    }

    location /remote2/ {
        try_files $uri $uri/ =404;
    }

    location /remote3/ {
        try_files $uri $uri/ =404;
    }

    # 可选:根路径默认跳转至Shell应用
    location / {
        return 301 /shell/;
    }
}

关键说明:/shell/规则中的try_files会优先匹配静态文件,匹配失败时自动转发到/shell/index.html,确保Angular路由能接管所有子路径请求,而非返回根目录的默认页面。

二、确认模块baseHref配置

每个模块的project.json中,baseHref必须与部署路径严格对应,且末尾斜杠不能省略:

  • Shell模块:
"build": {
  "executor": "@angular-devkit/build-angular:browser",
  "options": {
    "outputPath": "dist/shell",
    "baseHref": "/shell/",
    ...
  }
}
  • Remote1模块:
"build": {
  "executor": "@angular-devkit/build-angular:browser",
  "options": {
    "outputPath": "dist/remote1",
    "baseHref": "/remote1/",
    ...
  }
}

Remote2、Remote3模块以此类推。

三、验证Webpack Remote地址配置

生产环境的webpack.prod.config.js中,Remote的地址必须指向Nginx根目录下的实际路径,而非本地开发的端口地址:

const ModuleFederationPlugin = require('@module-federation/webpack/src/ModuleFederationPlugin');

module.exports = {
  plugins: [
    new ModuleFederationPlugin({
      name: 'shell',
      remotes: {
        remote1: 'remote1@/remote1/remoteEntry.js',
        remote2: 'remote2@/remote2/remoteEntry.js',
        remote3: 'remote3@/remote3/remoteEntry.js',
      },
      ...
    }),
  ],
};

四、检查Shell路由配置

确保Shell应用中加载Remote模块的路由路径与部署路径匹配:

import { Routes } from '@angular/router';

const routes: Routes = [
  {
    path: 'remote1',
    loadChildren: () => import('remote1/Module').then(m => m.Remote1Module)
  },
  {
    path: 'remote2',
    loadChildren: () => import('remote2/Module').then(m => m.Remote2Module)
  },
  {
    path: 'remote3',
    loadChildren: () => import('remote3/Module').then(m => m.Remote3Module)
  },
  { path: '', redirectTo: '', pathMatch: 'full' }
];

五、验证部署文件结构

确保Nginx根目录的文件结构如下(多余的根index.html建议删除,避免干扰):

/usr/share/nginx/html/
├── shell/
│   ├── index.html
│   ├── main.js
│   └── 其他Shell构建产物
├── remote1/
│   ├── remoteEntry.js
│   ├── main.js
│   └── 其他Remote1构建产物
├── remote2/
│   └── 对应构建产物
└── remote3/
    └── 对应构建产物

最终测试步骤

  1. 重新构建所有模块,确保baseHref生效
  2. 替换Nginx配置并重启服务
  3. 访问/shell,导航至/shell/remote1,验证Remote模块是否正常嵌入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:35:44