map "$request_uri $http_referer $http_user_agent $http_cookie" $flag {
    default 0;
    # rules
    "~test" 1;
    "~1234" 1;
    # …
location ~ example {
    if (\$flag = 1) {
        access_log /var/log/nginx/flag.log;

Is there any way to know which of the map rules and what part of $request_uri $http_referer $http_user_agent $http_cookie matched?

I need this for debugging purposes. If the log gets flooded, it's hard to tell which of the map rules has an error and causes false positives.


You can use a named capture in a map. The defined variable can be used to form the map result or anywhere else in your configuration after the map has been evaluated.

For example:

map ... $flag {
    default         0;
    ~(?<mymap>test) 1;
    ~(?<mymap>1234) 1;
if ($flag) { ... }

The if block will evaluate the value of $flag and if the regular expression containing the named capture is reached, the value of $mymap will be set to test or 1234.

  • this is perfect, thank you! – aexl Jan 3 '20 at 16:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.