动态子域名配置方案

无限客户子域名自动识别系统

---

## **1. 方案概述**

### 目标

- 无需为每个客户单独配置DNS解析和服务器

- 通过子域名自动识别客户身份(如 `client123.yourdomain.com`)

- 所有客户共用同一套网站代码,动态加载定制内容

---

## **2. 配置步骤**

### 2.1 DNS通配符解析

| 配置项 | 值 |

|--------------|---------------------|

| 记录类型 | A记录 |

| 主机名 | `*` |

| 记录值 | 服务器IP地址 |

| TTL | 600(建议值) |

**操作截图**:

---

### 2.2 服务器配置(Nginx示例)

```nginx

server {

listen 80;

server_name ~^(?.+)\.test\.com$;

root /var/www/main-site;

# 将子域名传递到后端

location / {

proxy_set_header X-Subdomain $subdomain;

try_files $uri $uri/ /index.php?$args;

}

# 其他安全配置...

}

```

---

### 2.3 HTTPS证书(Let's Encrypt)

```bash

# 安装Certbot

sudo apt install certbot python3-certbot-nginx

# 申请通配符证书(需DNS验证)

certbot certonly --manual --preferred-challenges=dns -d *.test.com

```

---

## **3. 后端代码示例**

### 3.1 PHP获取子域名

```php

<?php

// 提取子域名

$subdomain = explode('.', $_SERVER['HTTP_HOST'])[0];

// 查询数据库(示例)

$pdo = new PDO('mysql:host=localhost;dbname=clients', 'user', 'password');

$stmt = $pdo->prepare("SELECT * FROM clients WHERE subdomain = ?");

$stmt->execute([$subdomain]);

$client = $stmt->fetch();

// 输出定制内容

echo "欢迎访问客户: " . htmlspecialchars($client['name']);

?>

```

### 3.2 Node.js (Express)

```javascript

app.use(async (req, res, next) => {

const subdomain = req.subdomains[0];

const client = await db.query('SELECT * FROM clients WHERE subdomain = ?', [subdomain]);

req.client = client;

next();

});

app.get('/', (req, res) => {

res.render('client-page', { client: req.client });

});

```

---

## **4. 安全与优化**

| 类别 | 措施 |

|------------|----------------------------------------------------------------------|

| **安全** | 1. 子域名合法性校验(正则过滤特殊字符)
2. 防止SQL注入 |

| **性能** | 1. Redis缓存客户配置
2. CDN加速静态资源 |

| **监控** | 1. 日志记录子域名访问
2. 异常流量告警 |

---

## **5. 流程图**

```plaintext

客户访问 client123.test.com

DNS通配符解析 → 指向服务器IP

Nginx捕获子域名 "client123"

后端查询数据库 → 返回客户配置

渲染定制化页面

```

---

## **6. 常见问题**

**Q1: 最多支持多少个子域名?**

无需限制,由数据库容量决定。

**Q2: 国内服务器是否需要备案?**

主域名已备案即可,子域名无需单独备案。

**Q3: 如何防止子域名被恶意注册?**

建议添加子域名白名单机制。