一、为什么需要配置二级域名?
在Web开发中,二级域名(如api.example.com、admin.example.com)是提升系统可维护性和安全性的重要手段。通过将不同功能模块(如API接口、后台管理系统)分配到独立二级域名,开发者可以实现:
- 功能隔离:API服务与前端页面分离,便于独立部署和扩展
- 安全增强:为不同域名配置差异化安全策略(如CORS规则、HTTPS配置)
- 负载优化:根据业务特点分配不同服务器资源
- SEO友好:清晰的域名结构有助于搜索引擎识别内容分类
以某电商平台为例,其架构包含:
www.example.com:主站页面api.example.com:RESTful API接口admin.example.com:后台管理系统
这种结构使系统各模块解耦,当API服务需要升级时,不会影响主站访问。
二、配置前的准备工作
1. DNS解析设置
在域名注册商(如阿里云、腾讯云)的DNS管理界面,需要添加以下记录:
类型:CNAME主机记录:api记录值:您的服务器公网IP或已解析的域名TTL:默认值(通常3600秒)
验证DNS生效时间可通过dig api.example.com命令(Linux/Mac)或nslookup api.example.com(Windows)检查解析结果。
2. 服务器环境准备
确保服务器已安装:
- Nginx最新稳定版(建议1.18+)
- OpenSSL(用于HTTPS配置)
- 防火墙开放80/443端口
推荐使用以下命令安装Nginx(Ubuntu示例):
sudo apt updatesudo apt install nginxsudo systemctl start nginxsudo systemctl enable nginx
三、Nginx配置核心步骤
1. 基础配置文件结构
Nginx配置采用模块化设计,推荐在/etc/nginx/conf.d/目录下创建独立配置文件(如api.example.com.conf),内容框架如下:
server {listen 80;server_name api.example.com;# 日志配置access_log /var/log/nginx/api.access.log;error_log /var/log/nginx/api.error.log;# 核心路由配置location / {proxy_pass http://localhost:3000; # 转发到后端服务proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
2. HTTPS配置(关键安全项)
使用Let’s Encrypt免费证书的配置示例:
server {listen 443 ssl;server_name api.example.com;ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;# 安全增强配置ssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers HIGH:!aNULL:!MD5;ssl_prefer_server_ciphers on;# HSTS头配置add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}
证书申请建议使用Certbot工具自动化处理:
sudo apt install certbot python3-certbot-nginxsudo certbot --nginx -d api.example.com
3. 高级路由配置技巧
3.1 基于路径的路由
location /v1/ {proxy_pass http://api-v1-service;}location /v2/ {proxy_pass http://api-v2-service;}
3.2 WebSocket支持
location /ws/ {proxy_pass http://websocket-backend;proxy_http_version 1.1;proxy_set_header Upgrade $http_upgrade;proxy_set_header Connection "upgrade";}
3.3 静态资源缓存
location ~* \.(jpg|jpeg|png|css|js)$ {expires 30d;add_header Cache-Control "public";}
四、常见问题解决方案
1. 配置不生效问题排查
- 检查语法错误:
sudo nginx -t - 查看错误日志:
tail -f /var/log/nginx/error.log - 确认配置文件加载:
nginx -T | grep server_name
2. 跨域问题处理
location / {if ($request_method = 'OPTIONS') {add_header 'Access-Control-Allow-Origin' '*';add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';add_header 'Access-Control-Max-Age' 1728000;return 204;}add_header 'Access-Control-Allow-Origin' '*';proxy_pass http://backend;}
3. 性能优化建议
-
启用Gzip压缩:
gzip on;gzip_types text/plain text/css application/json application/javascript;gzip_min_length 1000;
-
连接池配置:
upstream api_backend {server 127.0.0.1:3000;keepalive 32;}
五、完整配置示例
以下是一个生产环境可用的完整配置:
server {listen 80;server_name api.example.com;return 301 https://$host$request_uri;}server {listen 443 ssl http2;server_name api.example.com;# SSL配置ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;# 安全头add_header X-Frame-Options "SAMEORIGIN";add_header X-Content-Type-Options "nosniff";add_header X-XSS-Protection "1; mode=block";# 核心路由location / {proxy_pass http://api_upstream;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;proxy_set_header X-Forwarded-Proto $scheme;# 超时设置proxy_connect_timeout 60s;proxy_read_timeout 300s;proxy_send_timeout 300s;}# 健康检查端点location /health {access_log off;return 200 "OK";}}upstream api_upstream {server 127.0.0.1:8080;keepalive 32;}
六、最佳实践建议
- 配置版本控制:使用Git管理Nginx配置,便于回滚和协作
- 自动化部署:通过Ansible/Puppet实现配置批量更新
- 监控告警:集成Prometheus监控Nginx状态码分布
- 定期审计:每季度检查SSL证书有效期和安全头配置
- 性能基准测试:使用wrk工具测试不同配置下的QPS
通过系统掌握上述技巧,开发者可以高效完成Nginx二级域名配置,构建出高性能、高可用的Web服务架构。实际部署时建议先在测试环境验证配置,再逐步推广到生产环境。