NGINX:仅根据特定 URL 的 cookie 重定向用户

问题描述 投票:0回答:3

我正在构建一个封闭的社交网络,目前当用户未登录时,他们将始终被重定向到我的域的主页。

我想做的是执行以下操作:

  1. 使用 NGINX 检查用户是否登录(通过检查 cookie),然后当他们访问主页 (mydomain.com) 时重定向到 mydomain.com/newsfeed。

  2. 此检查仅应在用户浏览主页时应用,并且不应在任何其他网址上工作(否则它们将始终被重定向)。

我对 NGINX 非常陌生,并且查看了各种使用 cookie 进行重定向的教程,但未能得到答案(最值得注意的是,将重定向限制为仅限主页)。

提前致谢!

redirect cookies nginx server
3个回答
15
投票

最终正确解决方案:

location ~* ^/$ {
 if ($http_cookie ~* "wordpress_logged_in") {
    return 301 http://example.com/newsfeed/;
 }
}

6
投票

假设我有一块饼干,如下所示:

name=value

server {
    listen 80;
    server_name mydomain.com;

    location ~* ^/$ {
        if ($cookie_name = "value") {
            return 301 http://example.com/newsfeed/;
        }
    }
}

位置块将仅匹配主页,检查cookie是否存在(您也可以只使用

if ($cookie_name)
),如果存在,则将用户重定向到
http://example.com/newsfeed/


0
投票

如果您想确保仅重定向 html 请求,请参阅此:

http {

map $http_accept $redirectable_signal {
    default "not_redirectable";
    ~.*text/html.* ""; # text/html requests can be redirected
}

map "$cookie_accessToken$redirectable_signal" $should_redirect {
    default 0;
    "" 1; # no cookie and it's an text/html request
}

server {
    # ...

    location / {
        if ($should_redirect) {
            return 302 /Authenticate?redirectScheme=$scheme&redirectHost=$host&redirectUrl=$request_uri;
        }
    }
}

}
© www.soinside.com 2019 - 2024. All rights reserved.