Reputation: 187
I'm trying to redirect users with NGINX to a different virtual host if they don't have an auth
cookie in the request they make. That is, when they visit foo.com
, if an auth
cookie is present, then they should see foo.com
; if they lack an auth
cookie, they should see signup.foo.com
.
I've read through "If is Evil" from NGINX, and I was able to successfully check whether users had cookies. I did that by doing:
if ($cookie_auth) {
redirect 301 https://signup.foo.com;
}
...
But, of course, that's doing the opposite of what I want to happen. I also tried doing a map, like the following:
map $cookie_auth $no_auth {
default 0;
'' 1;
}
server {
...
if ($no_auth) { return 301 https://signup.foo.com; }
...
}
But that seemed to redirect everything to signup.foo.com. Pretty much the essence of my question is how to use a NOT
operator in NGINX. Something like if (!$cookie_auth)
, for example.
Upvotes: 4
Views: 10442
Reputation: 10314
You could test for an empty string:
server {
server_name www.example.com;
if ($cookie_auth = "") {
return 200 "cookie_auth is not set
";
}
if ($cookie_auth) {
return 200 "cookie_auth is set =>$cookie_auth<=
";
}
return 200 "no match
";
}
Testing with curl:
curl --cookie auth=123 www.example.com
cookie_auth is set =>123<=
curl --cookie auth= www.example.com
cookie_auth is not set
curl www.example.com
cookie_auth is not set
Upvotes: 10