NGINX and environment variables from configuration

2019-05-16 11:58发布

问题:

I'm trying to set some environment variables to nginx via it's configuration file. I'm using nginx/0.8.53 and it's not working.

server {
    listen 80;
    server_name localdictus;
    root /opt/vdmo_dictus/public;   # <--- be sure to point to 'public'!
    passenger_enabled on;
    rails_env development;
    env VDMO_MANDANT = "somevalue";
    }

This is the error message:

unknown directive "env" in /opt/nginx/conf/nginx.conf:43

The documentation tells me that there is an "env" command... so what I'm doing wrong ?? http://wiki.nginx.org/CoreModule#env

setting the environment variables via export on the shell is not an option for my application by the way.

Here are the lines:

37:    server {
38:    listen 80;
39:    server_name localdictus;
40:    root /opt/vdmo_dictus/public;   # <--- be sure to point to 'public'!
41:    passenger_enabled on;
42:    rails_env development;
43:    env VDMO_MANDANT = "somevalue";
44:    }

Regards,

Alex

回答1:

From the documentation you linked to the "Context" for the env directive is main, not server. Put the directive outside of your server { ... } block (outside of any block).

See also this discussion. I do not believe that the env directive does what you are looking for.



回答2:

Don't pass the env directive. Just use the -E flag when starting nginx:

 sudo -E /usr/local/nginx/sbin/nginx


回答3:

A solution for setting the environment variables for a rails app using nginx.

Your RAILS_ROOT , for example, is : /opt/myapp_MANDANT

Then the following code would extract MANDANT from the RAILS_ROOT path and set in to the rails env.

split = RAILS_ROOT.split("_")
puts split.inspect


if split.size > 1
    ENV['VDMO_SYSTEM'] = split[2]
    ENV['VDMO_MANDANT'] = split[1]
elsif split.size > 0
    ENV['VDMO_SYSTEM'] = nil
    ENV['VDMO_MANDANT'] = split[1]
end

put this code in your environment.rb file to work.

A nice way for using this approch is mount with the --bind option.

Example:

   mkdir railsapp_mandant
   mount -t /originalsource /railsapp_mandant

then set the public path of the rails app to to /originalsource/public/ instead of /railsapp_mandant/public/