一、为什么需要配置二级域名?
在Web开发中,二级域名(如api.example.com、blog.example.com)是常见的需求。其核心价值体现在:
- 功能隔离:通过不同子域名区分前后端服务(如
api.example.com负责API,www.example.com负责前端) - 安全增强:可为不同子域名配置独立SSL证书,实现更细粒度的HTTPS控制
- 负载优化:将静态资源(
static.example.com)与动态内容分离,提升服务器性能 - 品牌统一:保持主域名一致性,同时支持多业务线独立运营
以电商网站为例,配置pay.example.com处理支付,user.example.com管理账户,可显著降低系统耦合度。
二、配置前的必要准备
1. DNS解析设置
需在域名服务商处添加CNAME记录:
子域名 记录类型 值api CNAME 服务器IP或主域名
关键点:
- 等待DNS生效(通常5-30分钟)
- 避免循环CNAME(如A指向B,B又指向A)
- 推荐使用TTL 300秒加速更新
2. 服务器环境要求
- Nginx版本≥1.12(支持HTTP/2)
- 防火墙开放80/443端口
- 足够的系统资源(建议2核4G起)
三、Nginx配置实战
1. 基础配置模板
server {listen 80;server_name api.example.com; # 关键配置项location / {proxy_pass http://localhost:3000; # 后端服务地址proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
参数详解:
server_name:必须精确匹配子域名proxy_pass:建议使用内网IP避免DNS解析延迟proxy_set_header:确保后端获取真实客户端信息
2. HTTPS配置方案
方案一:独立证书
server {listen 443 ssl;server_name api.example.com;ssl_certificate /path/to/api.example.com.crt;ssl_certificate_key /path/to/api.example.com.key;# 安全增强配置ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;...}
方案二:通配符证书(推荐)
server {listen 443 ssl;server_name *.example.com;ssl_certificate /path/to/wildcard.crt;ssl_certificate_key /path/to/wildcard.key;...}
选择建议:
- 5个子域名以下:独立证书
- 5+子域名:通配符证书(年费约$150-$500)
3. 高级配置技巧
3.1 负载均衡
upstream api_servers {server 10.0.0.1:3000 weight=3;server 10.0.0.2:3000;server 10.0.0.3:3000 backup;}server {...location / {proxy_pass http://api_servers;}}
3.2 静态资源优化
server {server_name static.example.com;location / {root /var/www/static;expires 1y;add_header Cache-Control "public";}}
3.3 跨域支持
server {...location / {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';}}
四、常见问题解决方案
1. 配置不生效
排查步骤:
- 执行
nginx -t测试配置 - 检查
nginx.conf是否包含include /etc/nginx/conf.d/*.conf; - 查看错误日志:
tail -f /var/log/nginx/error.log
2. 502 Bad Gateway
常见原因:
- 后端服务未启动
- 防火墙阻止连接
- 代理超时设置过短
解决方案:
location / {proxy_connect_timeout 60s;proxy_read_timeout 60s;proxy_send_timeout 60s;...}
3. HTTPS证书警告
检查项:
- 证书链是否完整(需包含中间证书)
- 证书有效期
- 域名是否与证书匹配
五、性能优化建议
- 启用HTTP/2:
server {listen 443 ssl http2;...}
- 启用Gzip压缩:
gzip on;gzip_types text/plain application/json;gzip_min_length 1k;
- 连接池优化:
upstream api_servers {keepalive 32;server 10.0.0.1:3000;}
六、自动化配置方案
推荐使用Ansible实现批量配置:
- name: Configure Nginx subdomainhosts: web_serverstasks:- name: Create config filetemplate:src: subdomain.conf.j2dest: /etc/nginx/conf.d/{{ subdomain }}.confnotify:- Reload Nginx
七、安全加固措施
- 限制访问IP:
server {allow 192.168.1.0/24;deny all;...}
- 禁用危险方法:
if ($request_method !~ ^(GET|HEAD|POST)$ ) {return 444;}
- 定期更新Nginx:
# Ubuntu系统sudo apt update && sudo apt upgrade nginx
通过以上配置,开发者可以高效实现二级域名管理,同时确保系统安全性和性能。实际部署时建议先在测试环境验证,再逐步推广到生产环境。