Like other programming platforms, nginx can also declare variables in a very simple way
We can use the set directive to declare variables. We will have 3 types of variables:
We will have the declaration structure as follows
set $<variable_name> <variable_value>;
Example
# set name "Farhan"
# set age 25
# set is_working true
In addition, nginx also has a built-in variable system that allows us to use at any time.
Example
events {
}
http {
server {
listen 80;
server_name nglearns.test;
return 200 "Host - $host\nURI - $uri\nArgs - $args\n";
}
}
Performing request
# curl http://nglearns.test/user?name=Farhan
Result
# Host - nglearns.test
# URI - /user
# Args - name=Farhan
In the example above, the variables $host and $uri have values related to the root address and URI, and the variable $args shows all Search Query Params on the URL.
In case you need to retrieve a specific value of Search Query Params, follow the example below:
events {
}
http {
server {
listen 80;
server_name nglearns.test;
set $name $arg_name;
return 200 "Name - $name\n";
}
}
Try querying
curl http://nglearns.test?name=Farhan
result
# Name - Farhan
In the example above, we can easily retrieve the name information separately.