你如何有条件地在 Nginx vhost 中包含文件?

Xeo*_*oss 16 configuration nginx fastcgi

在下面的行中,我可能有一个特定于站点的配置文件,其中包含该站点独有的其他fastcgi_params。如果这个文件存在,我想加载它。

server {
        listen 80 default;
        server_name _;
        root /path/www/$host;

        # Pass PHP scripts to php-fastcgi listening on port 9000
        location ~ \.php {
                include fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;


                if (-f /path/www/$host/nginx.conf) {
                        include /path/www/$host/nginx.conf;
                }
        }
}
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,我得到的错误是:

nginx: [emerg] "include" 指令在这里是不允许的......

更新

我认为与其单独检查,不如让include 来检查我。

server {
        listen 80 default;
        server_name _;
        root /path/www/$host;

        # Pass PHP scripts to php-fastcgi listening on port 9000
        location ~ \.php {
                include fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;

                include /path/www/$host/*.nginx;
        }
}
Run Code Online (Sandbox Code Playgroud)

但是,这似乎不起作用。

小智 34

嗯,这是相当古老的,但无论如何,我找到了一个解决方法。

我有一个以这种风格配置的虚拟主机的设置:

/etc/nginx/sites-enabled/site.com.conf
Run Code Online (Sandbox Code Playgroud)

而不是检查文件是否存在(这是不可能的),我只是这样做:

include /etc/nginx/sites-customizations/site.com.*.conf
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我可以简单地在sites-customizations-folder 中创建一个文件,按照我的约定,该文件的名称与主配置相同。它的*工作原理与 if 非常相似,因为如果没有额外的配置文件,它不会中断。如果您愿意,这也使您能够在单独的文件中添加多个额外的配置。


Sha*_*den 10

include在服务器启动期间做它的事情 -正如你发现的那样$host,不能使用运行时变量,也不能在if上下文中使用它。

您需要server为不同的主机拆分块。对不起!


Alb*_*ore 7

我利用glob()了 nginx 在include指令中使用的函数模式扩展,并且在我的 Debian 服务器上运行良好。

在您的情况下,请尝试替换此行:

include /path/www/$host/nginx.conf;
Run Code Online (Sandbox Code Playgroud)

有了这个:

include /path/www/<hostname>/nginx[.]conf;
Run Code Online (Sandbox Code Playgroud)

它是一个只匹配一个文件的文件掩码,如果文件不存在,它不会让 nginx 抱怨。但是,include 指令中不允许使用变量,因此您必须在<hostname>. 我们必须创建一个脚本来生成单独的 .conf 文件(每个虚拟主机一个)。

编辑

正如Gerald Schneider指出的那样,我建议保留$host替代品,这是不允许的。我已经改变了上面的建议。

  • “nginx[.]conf”的包含不起作用,它不包含该文件。没有括号的 Bit 仅当文件存在时才起作用。(使用版本 1.18.0 进行测试)但是 `nginx*.conf` 工作正常(如果文件存在)并且如果文件不存在也不会抱怨。 (2认同)

Tit*_*iti 6

我知道这很旧,但解决方案可能会帮助像我一样寻找答案的人。

我有一堆重定向,我只需要为特定主机包含这些重定向,虽然指令中include不允许,但if我最终在if包含的文件中添加了...

所以我include /etc/nginx/conf.d/redirects在那个文件中有一个and :

if ($host = "www.example.com") {
    # Some conf or redirects for this site only.
}
Run Code Online (Sandbox Code Playgroud)