Skip to main content
 首页 » 编程设计

nginx之两个子域配置

2024年05月06日33Free-Thinker

我是 Nginx 新手,我正在尝试让子域正常工作。

我想做的是获取我的域名(我们称之为 example.com)并添加:

  • sub1.example.com
  • sub2.example.com,并且还有
  • www.example.com 可用。

我知道如何使用 Apache 来做到这一点,但 Nginx 确实令人头疼。

我运行的是 Debian 6。

我当前的/etc/nginx/sites-enabled/example.com:

server { 
    server_name www.example.com example.com; 
    access_log /srv/www/www.example.com/logs/access.log; 
    error_log /srv/www/www.example.com/logs/error.log; 
    root /srv/www/www.example.com/public_html; 
 
    location / { 
        index  index.html index.htm; 
    } 
 
    location ~ \.php$ { 
        include /etc/nginx/fastcgi_params; 
        fastcgi_pass 127.0.0.1:9000; 
        fastcgi_index index.php; 
        fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name; 
    } 
} 

它正在努力为 example.com 和 www.example.com 提供服务。

我尝试在同一个文件中添加第二个服务器 block ,例如:

server { 
        server_name www.example.com example.com; 
        access_log /srv/www/www.example.com/logs/access.log; 
        error_log /srv/www/www.example.com/logs/error.log; 
        root /srv/www/www.example.com/public_html; 
 
        server { 
            server_name sub1.example.com; 
            access_log /srv/www/example.com/logs/sub1-access.log; 
            error_log /srv/www/example.com/logs/sub1-error.log; 
            root /srv/www/example.com/sub1; 
    } 
        location / { 
            index  index.html index.htm; 
        } 
 
        location ~ \.php$ { 
            include /etc/nginx/fastcgi_params; 
            fastcgi_pass 127.0.0.1:9000; 
            fastcgi_index index.php; 
            fastcgi_param SCRIPT_FILENAME /srv/www/www.example.com/public_html$fastcgi_script_name; 
        } 
} 

运气不好。有任何想法吗?我非常感谢任何反馈。

请您参考如下方法:

错误是将服务器 block 放在服务器 block 中,您应该关闭主服务器 block ,然后为子域打开一个新服务器 block

server { 
    server_name example.com; 
    # the rest of the config 
} 
server { 
    server_name sub1.example.com; 
    # sub1 config 
} 
server { 
    server_name sub2.example.com; 
    # sub2 config 
}