Nginx 站点配置模板和变量

Ale*_*man 7 configuration nginx

嗨,我想设置一个简单的 nginx 配置,我读到您可以使用设置变量,set $variable content;但到目前为止我还没有运气...

以下是我到目前为止提出的/我正在努力实现的目标:

server {

##################################################
# Set variables
set $port               80;                        # e.g. 80 or 443;
set $domain         domain.com *.domain.com;   # e.g. www.domain.com or just domain.com
set $subdomain          false;                     # e.g. subdomain in subdomain.domain.com or false
set type               live;                      # live, dev or stage

##################################################
# Include /web/sites configuration template
include /etc/nginx/site-config-template;

}
Run Code Online (Sandbox Code Playgroud)

以下是 /etc/nginx/site-config-template 的内容:

##################################################
# If $subdomain is not false at slash
if ( $subdomain ) {
    set $subdomain "{$subdomain}/";
}

##################################################
# Define server main variables
listen          $port;
server_name     $domain;
root            /web/sites/$domain/$subdomain$type/public_html/current/;
index           index.php index.html;

##################################################
# Logs
access_log  /web/sites/$domain/$subdomain$type/logs/access.log;
error_log   /web/sites/$domain/$subdomain$type/logs/error.log;

##################################################
# push all to index.php
location / {
    try_files $uri $uri/ /index.php$args;
}

##################################################
# pass php files to fastcgi
location ~ \.php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_param SITE_TYPE $type;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
}
Run Code Online (Sandbox Code Playgroud)

我是否无法在配置文件中以这种方式设置变量,或者我只是做错了什么?

小智 12

nginx的常见问题是关于这一主题非常明确:

问:是否有正确的方法使用 nginx 变量来缩短配置部分,将它们用作宏来使部分配置作为模板工作?

答:变量不应用作模板宏。变量在处理每个请求的运行时进行评估,因此与普通静态配置相比,它们的成本相当高。使用变量来存储静态字符串也是一个坏主意。相反,应该使用宏扩展和“包含”指令来更轻松地生成配置,并且可以使用外部工具完成,例如 sed + make 或任何其他通用模板机制。

使用外部工具构建配置是可行的方法。我用过m4+ make。我在我的一个项目中使用了自定义 Python 脚本。选择很多。

  • @Louis,你知道“宏观扩张”是什么意思吗?我错过了某种宏功能吗? (4认同)

Ale*_*man 5

简单的答案只是在每个域的基础上使用静态服务器配置,不要试图变得聪明。我设置了一个脚本来生成配置文件。