Nginx配置二级域名全攻略:开发中的实用技巧

一、为什么需要配置二级域名?

在Web开发中,二级域名(如api.example.comadmin.example.com)是提升系统可维护性和安全性的重要手段。通过将不同功能模块(如API接口、后台管理系统)分配到独立二级域名,开发者可以实现:

  1. 功能隔离:API服务与前端页面分离,便于独立部署和扩展
  2. 安全增强:为不同域名配置差异化安全策略(如CORS规则、HTTPS配置)
  3. 负载优化:根据业务特点分配不同服务器资源
  4. SEO友好:清晰的域名结构有助于搜索引擎识别内容分类

以某电商平台为例,其架构包含:

  • www.example.com:主站页面
  • api.example.com:RESTful API接口
  • admin.example.com:后台管理系统
    这种结构使系统各模块解耦,当API服务需要升级时,不会影响主站访问。

二、配置前的准备工作

1. DNS解析设置

在域名注册商(如阿里云、腾讯云)的DNS管理界面,需要添加以下记录:

  1. 类型:CNAME
  2. 主机记录:api
  3. 记录值:您的服务器公网IP或已解析的域名
  4. TTL:默认值(通常3600秒)

验证DNS生效时间可通过dig api.example.com命令(Linux/Mac)或nslookup api.example.com(Windows)检查解析结果。

2. 服务器环境准备

确保服务器已安装:

  • Nginx最新稳定版(建议1.18+)
  • OpenSSL(用于HTTPS配置)
  • 防火墙开放80/443端口

推荐使用以下命令安装Nginx(Ubuntu示例):

  1. sudo apt update
  2. sudo apt install nginx
  3. sudo systemctl start nginx
  4. sudo systemctl enable nginx

三、Nginx配置核心步骤

1. 基础配置文件结构

Nginx配置采用模块化设计,推荐在/etc/nginx/conf.d/目录下创建独立配置文件(如api.example.com.conf),内容框架如下:

  1. server {
  2. listen 80;
  3. server_name api.example.com;
  4. # 日志配置
  5. access_log /var/log/nginx/api.access.log;
  6. error_log /var/log/nginx/api.error.log;
  7. # 核心路由配置
  8. location / {
  9. proxy_pass http://localhost:3000; # 转发到后端服务
  10. proxy_set_header Host $host;
  11. proxy_set_header X-Real-IP $remote_addr;
  12. }
  13. }

2. HTTPS配置(关键安全项)

使用Let’s Encrypt免费证书的配置示例:

  1. server {
  2. listen 443 ssl;
  3. server_name api.example.com;
  4. ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
  5. ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
  6. # 安全增强配置
  7. ssl_protocols TLSv1.2 TLSv1.3;
  8. ssl_ciphers HIGH:!aNULL:!MD5;
  9. ssl_prefer_server_ciphers on;
  10. # HSTS头配置
  11. add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
  12. }

证书申请建议使用Certbot工具自动化处理:

  1. sudo apt install certbot python3-certbot-nginx
  2. sudo certbot --nginx -d api.example.com

3. 高级路由配置技巧

3.1 基于路径的路由

  1. location /v1/ {
  2. proxy_pass http://api-v1-service;
  3. }
  4. location /v2/ {
  5. proxy_pass http://api-v2-service;
  6. }

3.2 WebSocket支持

  1. location /ws/ {
  2. proxy_pass http://websocket-backend;
  3. proxy_http_version 1.1;
  4. proxy_set_header Upgrade $http_upgrade;
  5. proxy_set_header Connection "upgrade";
  6. }

3.3 静态资源缓存

  1. location ~* \.(jpg|jpeg|png|css|js)$ {
  2. expires 30d;
  3. add_header Cache-Control "public";
  4. }

四、常见问题解决方案

1. 配置不生效问题排查

  • 检查语法错误:sudo nginx -t
  • 查看错误日志:tail -f /var/log/nginx/error.log
  • 确认配置文件加载:nginx -T | grep server_name

2. 跨域问题处理

  1. location / {
  2. if ($request_method = 'OPTIONS') {
  3. add_header 'Access-Control-Allow-Origin' '*';
  4. add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
  5. add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
  6. add_header 'Access-Control-Max-Age' 1728000;
  7. return 204;
  8. }
  9. add_header 'Access-Control-Allow-Origin' '*';
  10. proxy_pass http://backend;
  11. }

3. 性能优化建议

  • 启用Gzip压缩:

    1. gzip on;
    2. gzip_types text/plain text/css application/json application/javascript;
    3. gzip_min_length 1000;
  • 连接池配置:

    1. upstream api_backend {
    2. server 127.0.0.1:3000;
    3. keepalive 32;
    4. }

五、完整配置示例

以下是一个生产环境可用的完整配置:

  1. server {
  2. listen 80;
  3. server_name api.example.com;
  4. return 301 https://$host$request_uri;
  5. }
  6. server {
  7. listen 443 ssl http2;
  8. server_name api.example.com;
  9. # SSL配置
  10. ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem;
  11. ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem;
  12. ssl_session_cache shared:SSL:10m;
  13. ssl_session_timeout 10m;
  14. # 安全头
  15. add_header X-Frame-Options "SAMEORIGIN";
  16. add_header X-Content-Type-Options "nosniff";
  17. add_header X-XSS-Protection "1; mode=block";
  18. # 核心路由
  19. location / {
  20. proxy_pass http://api_upstream;
  21. proxy_set_header Host $host;
  22. proxy_set_header X-Real-IP $remote_addr;
  23. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  24. proxy_set_header X-Forwarded-Proto $scheme;
  25. # 超时设置
  26. proxy_connect_timeout 60s;
  27. proxy_read_timeout 300s;
  28. proxy_send_timeout 300s;
  29. }
  30. # 健康检查端点
  31. location /health {
  32. access_log off;
  33. return 200 "OK";
  34. }
  35. }
  36. upstream api_upstream {
  37. server 127.0.0.1:8080;
  38. keepalive 32;
  39. }

六、最佳实践建议

  1. 配置版本控制:使用Git管理Nginx配置,便于回滚和协作
  2. 自动化部署:通过Ansible/Puppet实现配置批量更新
  3. 监控告警:集成Prometheus监控Nginx状态码分布
  4. 定期审计:每季度检查SSL证书有效期和安全头配置
  5. 性能基准测试:使用wrk工具测试不同配置下的QPS

通过系统掌握上述技巧,开发者可以高效完成Nginx二级域名配置,构建出高性能、高可用的Web服务架构。实际部署时建议先在测试环境验证配置,再逐步推广到生产环境。