简介:本文详细解析Nginx服务器中二级域名的配置方法,涵盖DNS解析、Nginx配置文件编写、SSL证书配置等核心环节,适合系统管理员和开发者参考。
二级域名是主域名下的子域名结构,形式为subdomain.example.com。在Nginx中配置二级域名具有重要实际价值:首先实现服务隔离,不同业务模块部署在不同二级域名下可提升系统稳定性;其次优化资源分配,通过独立配置文件管理不同域名的访问规则;最后增强安全性,可针对特定二级域名实施独立的安全策略。
典型应用场景包括:将API服务部署在api.example.com,静态资源部署在static.example.com,测试环境部署在test.example.com。这种结构使系统架构更清晰,便于维护和扩展。
需在域名注册商处添加CNAME记录或A记录。以阿里云DNS为例,登录控制台后进入域名解析页面,添加记录类型为CNAME的解析,主机记录填写二级域名前缀(如api),记录值填写服务器IP或已解析的主域名。
验证DNS解析是否生效可使用dig api.example.com或nslookup api.example.com命令,确认返回的IP地址与预期一致。解析生效时间通常为几分钟到几小时,取决于TTL设置。
确认已安装Nginx 1.18.0及以上版本,通过nginx -v命令查看版本。检查配置文件目录结构,推荐采用/etc/nginx/conf.d/存放独立配置文件,主配置文件nginx.conf通过include指令加载这些文件。
创建必要的目录结构:
mkdir -p /etc/nginx/conf.d/mkdir -p /var/www/api.example.com/html
在/etc/nginx/conf.d/api.example.com.conf中创建配置文件,基本结构如下:
server {listen 80;server_name api.example.com;location / {root /var/www/api.example.com/html;index index.html;try_files $uri $uri/ =404;}}
此配置监听80端口,当访问api.example.com时,从指定目录提供静态文件。
对于API服务,可配置upstream实现负载均衡:
upstream api_backend {server 10.0.0.1:8000 weight=3;server 10.0.0.2:8000;server 10.0.0.3:8000 backup;}server {listen 80;server_name api.example.com;location / {proxy_pass http://api_backend;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;}}
使用Let’s Encrypt免费证书:
# 安装certbotsudo apt install certbot python3-certbot-nginx# 获取证书sudo certbot --nginx -d api.example.com
自动生成的配置包含:
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 'TLS_AES_256_GCM_SHA384:...';ssl_prefer_server_ciphers on;}
检查步骤:
nginx -t测试配置语法server_name精确匹配域名(包括www前缀)/var/log/nginx/error.log对于高流量二级域名:
gzip on; gzip_types text/plain application/json;location ~* \.(jpg|jpeg|png)$ { expires 30d; }worker_processes auto;http2if ($request_method !~ ^(GET|HEAD|POST)$ ) { return 444; }ngx_http_limit_req_moduleadd_header Strict-Transport-Security "max-age=31536000" always;综合配置示例:
# HTTPS主配置server {listen 443 ssl http2;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_session_cache shared:SSL:10m;# 安全头配置add_header X-Frame-Options "SAMEORIGIN";add_header X-Content-Type-Options "nosniff";location / {proxy_pass http://api_backend;proxy_http_version 1.1;proxy_set_header Connection "";client_max_body_size 10m;}location /static/ {alias /var/www/api.example.com/static/;expires 30d;}}# HTTP重定向到HTTPSserver {listen 80;server_name api.example.com;return 301 https://$host$request_uri;}# 后端服务负载均衡upstream api_backend {zone api_backend 64k;least_conn;server 10.0.0.1:8000 max_fails=3 fail_timeout=30s;server 10.0.0.2:8000 max_fails=3 fail_timeout=30s;}
通过系统化的二级域名配置,可构建出高可用、高性能、高安全的Web服务体系。实际部署时建议先在测试环境验证配置,再逐步推广到生产环境。