Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Environment Variable or Parameter in nginx.conf

I try to add a proxy_pass in the nginx.conf like

location /example/ {
    proxy_pass   http://example.com;
}

But instead of hard coding http://example.com in the conf file I want to have this value in an environment variable.

How can I use environment variables in nginx.conf? Or is there a better way with nginx no have external configuration?

like image 969
Simon Martinelli Avatar asked Mar 05 '23 05:03

Simon Martinelli


2 Answers

If you want pure environment variables into nginx config, you will need implements some code in Lua Language:

https://blog.doismellburning.co.uk/environment-variables-in-nginx-config/

If you don't have a high load on this NGinx, I recommend implements this above solution.

In my specific case, to reduce CPU load, I prefer to use separated files with variables and a script in rc.local (or dockerfile) to change these files when launch the machine.

conf.d/exemple.conf

include backends/exemple.host;

location ~ ^/exemple {

    proxy_pass $exemple;
}

backends/exemple.host

set $exemple {BACKEND};

rc.local

sed -i "s@set \$exemple.*@set \$exemple $HOSTNAME\;@"  /etc/nginx/backends/exemple.host

To the last solution works, I need change the NGinx start order on O.S.

like image 51
Luis Costa Avatar answered Apr 10 '23 21:04

Luis Costa


You can use lua.

ex:

set_by_lua $curr_domain_name 'return os.getenv("DOMAIN")';
add_header Content-Security-Policy 'script-src  ${curr_domain_name}';

This worked for me.

like image 21
Madhuwantha Priyashan Avatar answered Apr 10 '23 22:04

Madhuwantha Priyashan