NGINX:检查Cookie是否不存在

时间:2019-09-18 15:25:56

标签: nginx

如果用户使用NGINX发出的请求中没有auth cookie,我将尝试将他们重定向到其他虚拟主机。也就是说,当他们访问foo.com时,如果存在auth Cookie,则他们应该看到foo.com;如果他们缺少auth Cookie,则应该看到signup.foo.com

我已经阅读了NGINX的“ If is Evil”,并且能够成功检查用户是否有cookie。我是这样做的:

if ($cookie_auth) {
     redirect 301 https://signup.foo.com;
}
...

但是,当然,这与我想发生的事情相反。我还尝试绘制地图,如下所示:

map $cookie_auth $no_auth {
    default 0;
    '' 1;
}

server {
     ...
     if ($no_auth) { return 301 https://signup.foo.com; }
     ...
}

但这似乎将所有内容重定向到signup.foo.com。我的问题的本质几乎是如何在NGINX中使用NOT运算符。例如,if (!$cookie_auth)之类的东西。

1 个答案:

答案 0 :(得分:0)

您可以测试一个空字符串:

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
";
}

使用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
相关问题