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

如何为Angular 14配置路由实现子域名分离(用户与管理端)

Angular 14 + Node 分离用户端与管理端域名配置方案

一、调整项目结构(多Angular应用)

采用Angular多项目工作区拆分用户端与管理端,便于独立维护和构建:

  • 初始化空工作区(未创建项目时执行):ng new workspace --create-application false
  • 创建用户端应用:ng generate application client --routing --style css
  • 创建管理端应用:ng generate application admin --routing --style css

最终项目结构:

workspace/
├── projects/
│   ├── client/       # 用户端(对应example.com)
│   └── admin/        # 管理端(对应console.example.com)
├── angular.json
└── server.js         # Node服务入口文件

二、Angular构建配置

修改angular.json,分别指定两个应用的构建输出目录:

  • 用户端:将projects.client.architect.build.options.outputPath设为dist/client
  • 管理端:将projects.admin.architect.build.options.outputPath设为dist/admin

生产构建命令:

  • 构建用户端:ng build client --configuration production
  • 构建管理端:ng build admin --configuration production

三、Node服务器配置(Express为例)

Node作为静态资源服务器+API服务,根据请求域名分发对应应用资源:

  1. 安装依赖:npm install express cors
  2. 编写server.js:
const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
app.use(cors());

// 托管静态资源
app.use(express.static(path.join(__dirname, 'dist/client')));
app.use(express.static(path.join(__dirname, 'dist/admin')));

// 处理SPA路由刷新问题
app.get('*', (req, res) => {
  if (req.hostname === 'example.com' || req.hostname === 'www.example.com') {
    res.sendFile(path.join(__dirname, 'dist/client/index.html'));
  } else if (req.hostname === 'console.example.com') {
    res.sendFile(path.join(__dirname, 'dist/admin/index.html'));
  } else {
    res.status(404).send('Not Found');
  }
});

// 配置API接口路由(按需添加)
// app.use('/api', require('./routes/api'));

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

四、DNS与反向代理配置(Nginx为例)

1. DNS解析

在域名服务商后台添加两条A记录:

  • example.com → 服务器公网IP
  • console.example.com → 同一服务器公网IP

2. Nginx反向代理配置

编辑Nginx配置文件(如/etc/nginx/conf.d/example.conf):

# 用户端域名配置
server {
  listen 80;
  server_name example.com www.example.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

# 管理端域名配置
server {
  listen 80;
  server_name console.example.com;

  location / {
    proxy_pass http://localhost:3000;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

若需HTTPS,可通过Let's Encrypt申请证书后添加SSL相关配置。

五、部署验证

  1. 执行Angular生产构建命令,生成静态资源到dist/目录
  2. 启动Node服务:node server.js
  3. 重启Nginx:sudo systemctl restart nginx
  4. 访问example.com验证用户端,访问console.example.com验证管理端

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 10:35:35