others-How to parse nginx request parameter dynamically?
1. Purpose
In this post, I would demonstrate how to parse the nginx quuery parameter using nginx directives. Just as the following picture shows:
2. The solution
2.1 The nginx config file
You can include this content in nginx:
server {
listen 81;
access_log /dev/stdout;
error_log /dev/stdout debug;
location /foo {
set $a 'hello $arg_name';
return 200 'a=$a';
}
}
Then we can test it:
⚡ root@launch-advisor-20191120 /etc/nginx curl http://localhost:81/foo\?name\=world
a=hello world#
There is very common built-in variable that does not have a fixed variable name. Instead, It has infinite variations. That is, all those variables whose names have the prefix arg_
, like $arg_foo
and $arg_bar
. Let’s just call it the $arg_XXX “variable group”. For example, the $arg_name
variable is evaluated to the value of the name
URI argument for the current request. Also, the URI argument’s value obtained here is not decoded yet, potentially containing the %XX
sequences.
For example:
location /test {
echo "name: $arg_name";
echo "class: $arg_class";
}
Then we test this interface with various different URI argument combinations:
$ curl 'http://localhost:8080/test'
name:
class:
$ curl 'http://localhost:8080/test?name=Tom&class=3'
name: Tom
class: 3
$ curl 'http://localhost:8080/test?name=hello%20world&class=9'
name: hello%20world
class: 9
3. Summary
In this post, I demonstrated how to parse request parameters using $arg_xxx
variable group. That’s it, thanks for your reading.