Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NGINX: Check if Cookies Don't Exist

Tags:

nginx

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.

like image 532
entersudonym Avatar asked Nov 01 '25 07:11

entersudonym


1 Answers

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
like image 145
Cole Tierney Avatar answered Nov 04 '25 02:11

Cole Tierney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!