3

I have a server with nginx that runs a site in production that should be replaced with a new site in the near future.

In order to be ready to that day - I'm preparing all the configurations that are required to run the new site.

What I would like to have is a global variable in the main nginx.conf that hold a string (e.g. 'old' or 'new' representing the site that should be active on the main domain example.com while the other site is on other.example.com.

I tried:

In nginx.conf

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

In /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;
    }
    ...
}

In /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;
    }
    ...
}

But, when running a configtest I get this error:

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

so I guess that the set directive is not allowed outside of a server block

Is there a way to achieve this functionality with a single variable across all nginx config files??

Thank you very much!

2
  • 1
    No. What for? I guess it's much easier to replace config files when you'll need
    – Alexey Ten
    Commented Jan 21, 2015 at 18:46
  • if something like variables was possible - it would have been much easier changing 1 to 0 in one place instead of handling 4 different files (HTTP+HTTPS for both sites).
    – Yaron U.
    Commented Jan 24, 2015 at 23:21

1 Answer 1

2

Just make a script. Sure an elegant solution built into nginx would be nice... but let's not forget the tools *nix affords us:

#!/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

... You may have to escape those semicolons.. Not sure...

1
  • Hi, thanks for replying! The script you wrote will make both files has the same server_name which will cause an error while trying to reload the server (it is easy to fix though). But, I've tried to find a solution that doesn't involve changing the content of the *.conf files.
    – Yaron U.
    Commented Jan 24, 2015 at 23:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .