A
A
Andrey2020-07-26 07:14:39
Nginx
Andrey, 2020-07-26 07:14:39

How to negate an argument in map?

There is such a design

map $request_method $cache_hit {
  "!~*post" 1;
  "~*!^post" 2;
  default 0;
}


Always returns 0. I need to write in such a way that if the method is not POST (GET, HEAD), then return not 0.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dodo512, 2020-07-26
Shults @noroots

I need to write so that if the method is not POST (GET, HEAD), then return not 0.

Those. if the method is POST, then return 0. Otherwise, return 1.
map $request_method $cache_hit {
  "~*post" 0;
  default 1;
}

The $request_method string is always in upper case, so no regular expression is needed.
map $request_method $cache_hit {
  POST    0;
  default 1;
}

As it turned out, the original task was to translate the following conditions onto the map:
set $cache_hit 1;

  # POST requests and urls with a query string should always go to PHP.
  if ($request_method = POST) {
    set $cache_hit 0;
  }

  if ($query_string != "") {
    set $cache_hit 0;
  }
   
  # Don't cache uris containing the following segments.
  if ($request_uri ~* "(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)") {
    set $cache_hit 0;
  }
   
  # Don't use the cache for logged-in users or recent commenters.
  if ($http_cookie ~* "comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in") {
    set $cache_hit 0;
  }

On map it can be done like this:
map $query_string $check_query_string {
  ""       0;
  default  1;
}

map $request_uri $check_request_uri {
  "~*(/wp-admin/|/xmlrpc.php|/wp-(app|cron|login|register|mail).php|wp-.*.php|/feed/|index.php|wp-comments-popup.php|wp-links-opml.php|wp-locations.php|sitemap(_index)?.xml|[a-z0-9_-]+-sitemap([0-9]+)?.xml)"  1;
  default  0;
}

map $http_cookie  $check_cookie {
  "~*comment_author|wordpress_[a-f0-9]+|wp-postpass|wordpress_logged_in"  1;
  default  0;
}


map "$request_method:$check_query_string:$check_request_uri:$check_cookie"  $cache_hit {
  "~^POST"    0;
  "~1"        0;
  default     1;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question