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

问题描述 投票:10回答:2

假设我为这样的域设置了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时遇到错误“这里不允许使用位置指令”。

nginx
2个回答
10
投票

你可以做:

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

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

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

include /etc/nginx/your-filename; 

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


19
投票

这是使用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; } }
© www.soinside.com 2019 - 2024. All rights reserved.