2

I need to do some conditional actions in nginx that is working as a proxy. Basically it all boils down to being able to set some nginx variable from external source. It can be a bash script or result generated by url or something like that.

For example:

set $var = [result of http request]

or

set $var = [result of bash command]

Are there any reliable solutions for this? Modules? If it's not good idea to this with nginx, what are the alternatives?

4
  • Well, it's too broad question. May be Nginx's Lua module would help.
    – Alexey Ten
    Jun 18, 2015 at 9:21
  • @AlexeyTen if you "promote" your comment about Lua to an answer with some example I'll be happy to accept it. Jun 23, 2015 at 20:35
  • If you be more specific, may be there are variables you want and no need for lua
    – Alexey Ten
    Jun 24, 2015 at 3:59
  • @AlexeyTen - no, there are no variables that could help me. I need to do conditional redirect or proxy depending on some factors. I can't code the logic I need into nginx config, that's why I need to be able to read data from external source. A simple example (although it's not the case here): redirect users to a different domain if user agent string meets specific criteria. Let's assume that simple regex on UA string is not enough and we need to code some sophisticated logic in a shell script to analyze the UA string. The script returns string that will be value of our nginx variable. Jun 24, 2015 at 7:25

2 Answers 2

2

The solution was to use lua module that executes simple lua script to perform necessary processing. Simple example:

location / {
  # Get device type from lua script.
  # Note: do not use content_by_lua as it's executed in separate context.
  set_by_lua_file $device_type 'device-detect.lua';

  # Do what needs to be done...
}

Whatever is returned by lua script lands inside $device_type variable.

Important thing to remember is that on most linux distributions, lua module is part of nginx-extras package which has to be installed instead of standard nginx-core.

0

Nginx has a lot of built-in variables[1] You could use something like this:

#Default to EN
set $vislang "EN";
#Discriminate language
if ($http_accept_language ~* "^fr") {
    set $vislang "FR";
}

A bash based solution could be a "sed -i nginx_conf_file && service nginx reload" but I think it is not very clean.

[1]http://nginx.org/en/docs/http/ngx_http_core_module.html#variables

1
  • I know that. But what I need is a way to set a variable value dynamically from external source (for example a script executed for each request) Jun 23, 2015 at 20:36

You must log in to answer this question.

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