Variables

Variables#

This page focuses on the aspects of using variables in nginx.

The following cell starts a container with Nginx, mounting the file variables_files/nginx.conf to the container as the Nginx configuration.

docker run -itd --rm \
    --name test_nginx_variables \
    -p 80:80 \
    -v $(pwd)/variables_files/nginx.conf:/etc/nginx/nginx.conf \
    nginx
47b9b6f0a56d9387bc5bdf7ea22307a82cfa9e2c57fe0110c00f31f7cd580911

Note: don’t forget to stop the container after all.

docker stop test_nginx_variables
test_nginx_variables

Custom variable#

Using set keyword you can define value your own variable.


The following cell defines an Nginx configuration that sets a variable test_variable and returns its value from the root.

cat << EOF > variables_files/nginx.conf
events {}

http {
    server {
        listen 80;
        set \$test_variable "VARIABLE VALUE";

        return 200 \$test_variable;
    }
}
EOF

docker exec test_nginx_variables nginx -s reload
2024/09/04 09:54:49 [notice] 57#57: signal process started

Now let’s try to request the created endpoint.

curl localhost:80
VARIABLE VALUE

Query parameters#

You can access query parameters of the request through the $arg_<param name> variable.


The following config tells nginx to return the value of the foo query parameter in a formated string.

cat << EOF > variables_files/nginx.conf
events {}

http {
    server {
        listen 80;
        return 200 "The value of foo: \$arg_foo";
    }
}
EOF

docker exec test_nginx_variables nginx -s reload
2024/12/10 06:37:42 [notice] 36#36: signal process started

Now, use curl to make a request to the service with query parameters.

curl "localhost:80?foo=hello&bar=world"
The value of foo: hello

The value of foo was used, while bar was ignored.

The following cell send request that doesn’t sepecifies value for foo parameter.

curl "localhost:80?bar=world"
The value of foo: 

There are no errors from nginx - everything is fine, just nothing is printed in the result.