在nginx.conf中重用域的配置语句

时间:2013-03-29 14:08:51

标签: nginx

假设我为这样的域设置了nginx配置:

server {

  root /path/to/one;
  server_name one.example.org;

  location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_pass    127.0.0.1:9000;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include         fastcgi_params;
  }

}

现在,如果我想添加另一个具有不同内容的域,是否可以重用上一个域中的等效语句,或者我是否必须为我想要支持的每个新域复制所有内容?

server {

  root /path/to/two; # different
  server_name two.example.org; # different

  location ~ \.php$ {
    try_files       $uri =404;
    fastcgi_pass    127.0.0.1:9000;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include         fastcgi_params;
  }

}

我尝试在location闭包之外移动server指令,但显然事情不会那样,因为我在重启nginx时遇到错误“此处不允许使用位置指令”。

2 个答案:

答案 0 :(得分:18)

这是使用nginx Map模块的一个很好的例子。 http://wiki.nginx.org/HttpMapModule

以下是我的尝试。它适用于我的devbox。注意

  1. map指令只能放在http块中。
  2. 声明map指令的性能损失可以忽略不计(参见上面的链接)
  3. 您可以自由拥有不同的根文件夹或端口号等。

    map $subdomain $root_folder {
      one  /path/to/one;
      two  /path/to/two;
    }
    
    map $subdomain $port_number {
      one 9000;
      two 9100;
    }
    
    server {
      listen  80;
      server_name  ~^(?P<subdomain>.+?)\.mydomain\.com$;
      root  $root_folder;
    
       location ~ \.php$ {
        try_files       $uri =404;
        fastcgi_pass    127.0.0.1:$port_number;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include         fastcgi_params;
      }
    }
    

答案 1 :(得分:10)

你可以这样做:

 server_name one.example.org two.example.org;

如果两者完全相同,除了域名

如果您只有类似的位置块,则可以将这些位置移动到单独的文件中,然后执行

include /etc/nginx/your-filename; 

在每个服务器块中轻松使用