基于全局variables在Nginx中设置server_name

我有一个nginx的服务器,运行一个生产站点,在不久的将来应该换成一个新的站点。

为了做好准备,我正在准备运行新站点所需的所有configuration

我想要的是在主要的nginx.conf中有一个全局variables,它包含一个string(例如'old''new'代表在主域example.com上活动的站点,而另一个站点在其他站点上other.example.com

我试过了:

nginx.conf

 http{ ... set $site_in_production 'new'; ... include /etc/nginx/conf.c/*.conf; } 

/etc/nginx/conf.d/example.com.conf

 server{ ... if($site_in_production='new'){ server_name other.example.com; } else { server_name example.com www.example.com; } ... } 

/etc/nginx/conf.d/new.example.com.conf

 server{ ... if($site_in_production='new'){ server_name example.com www.example.com; } else { server_name other.example.com; } ... } 

但是,当运行一个configtest我得到这个错误:

  nginx: [emerg] "set" directive is not allowed here in /etc/nginx/nginx.conf:XX 

所以我猜想set指令是不允许在server块之外的

有没有一种方法来实现所有nginxconfiguration文件中的单个variables的function?

非常感谢你!

只是做一个脚本。 当然,一个优雅的解决scheme内置到nginx将是很好的…但是,我们不要忘记工具*尼克斯提供给我们:

 #!/bin/bash for i in /etc/nginx/conf.d/*; do sed -i 's/server_name example.com www.example.com;/server_name other.example.com;/g' "$i"; done 

…你可能要逃避这些分号..不知道…