插件窝 干货文章 Nginx如何配置二级域名

Nginx如何配置二级域名

yourdomain 配置 server Nginx 426    来源:    2025-04-26

Nginx 二级域名配置指南

配置二级域名在Nginx中是一个常见需求,以下是详细的配置方法:

基本配置步骤

  1. DNS设置

    • 在域名管理面板中添加A记录或CNAME记录
    • 例如:subdomain.yourdomain.com指向服务器IP
  2. Nginx配置文件

server {
    listen 80;
    server_name subdomain.yourdomain.com;

    root /var/www/subdomain;
    index index.html index.php;

    location / {
        try_files $uri $uri/ =404;
    }

    # 其他配置...
}

常见场景配置

1. 静态网站

server {
    listen 80;
    server_name blog.yourdomain.com;

    root /var/www/blog;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

2. 反向代理到其他服务

server {
    listen 80;
    server_name api.yourdomain.com;

    location / {
        proxy_pass http://localhost:3000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

3. PHP应用(如WordPress)

server {
    listen 80;
    server_name shop.yourdomain.com;

    root /var/www/shop;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    }
}

HTTPS配置(推荐)

server {
    listen 443 ssl;
    server_name subdomain.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;

    root /var/www/subdomain;
    index index.html;

    # 其他SSL配置...
}

server {
    listen 80;
    server_name subdomain.yourdomain.com;
    return 301 https://$host$request_uri;
}

注意事项

  1. 每次修改Nginx配置后,需要测试并重新加载:

    sudo nginx -t
    sudo systemctl reload nginx
    
  2. 确保服务器防火墙开放了80和443端口

  3. 对于生产环境,建议总是使用HTTPS

  4. 可以使用通配符证书(*.yourdomain.com)来简化多个二级域名的SSL配置

  5. 如果使用Let's Encrypt获取证书,可以使用Certbot工具:

    sudo certbot --nginx -d subdomain.yourdomain.com
    

希望这些配置示例能帮助您成功设置Nginx二级域名。根据您的具体需求,可以调整上述配置。