显示404未find的子域,而不是显示根域的内容

我正在使用nginx。 我正在努力实现的是:

  • /var/www/domain.com获取内容的根域domain.com
  • /var/www/sub.domain.com获取内容的子域sub.domain.com
  • 任何其他子域*.domain.com (其中* != sub )应从/var/www/404获取内容

如果这不清楚:它类似于StackEchange设置,其中http://somesub.stackexchange.com/提供了一个404。

我在第一次使用两个不同server_name的服务器块成功。 但是,如果没有find匹配子域的服务器块,如何设置nginx链接到/var/www/404

使用基本设置,所有未find的子域将返回与根域相同的内容。

我想使这个通用的,所以,如果我添加另一个服务器块sub2.domain.com ,我不必改变404的块。

我现在使用的代码是:

 server { listen 80; server_name domain.com; root /var/www/domain.com; charset utf-8; location / { index index.php index.html; autoindex on; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } server { listen 80; server_name sub.domain.com; root /var/www/sub.domain.com; charset utf-8; location / { index index.php index.html; autoindex on; } location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } 

和Apache一样,Nginx将始终使用configuration列表中的第一个域作为其默认值。 在你的情况下,这意味着对于没有自己的configuration的任何域,它将selectdomain.com的configuration,因为这是第一个。

所以解决方法是简单地设置另一个只包含404页面的域,并且这是第一个列出的域。 然后,您可以添加任意数量的特定域名, 第一个只有在configuration文件中没有其他匹配的域名时才能使用。