Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if cookie does NOT contain specified content NGINX

There are countless tutorials on checking if a cookie exists and contains my content, in this case foobar.

How do I do the following assuming mycookie is the cookie that I want set.

if ($cookie_mycookie does not equal "foobar") {
  return 401;
}

I have tried the following to no avail.

if (!$http_mycookie ~* "foorbar" ) {
  return 401;
}

Thank you!

like image 279
blue ice Avatar asked Jun 26 '15 13:06

blue ice


1 Answers

In Nginx, each cookie is available in embedded variable $cookie_CookieName. In case you want to check cookie with name mycookie, you can do it using this configuration snippet:

if ($cookie_mycookie != "foobar") {
  return 401;
}

From nginx manual for the if command:

A condition maybe (among others):

  • Comparison of a variable with a string using the = and != operators;

  • Matching of a variable against a regular expression using the ~ (for case-sensitive matching) and ~* (for case-insensitive matching) operators.

  • Regular expressions can contain captures that are made available for later reuse in the $1..$9 variables.

  • Negative operators !~ and !~* are also available. If a regular expression includes the } or ; characters, the whole expressions should be enclosed in single or double quotes.

like image 148
Marki555 Avatar answered Sep 20 '22 23:09

Marki555