NGINX: Redirect a user based on cookie for a specific URL only

帅比萌擦擦* 提交于 2019-12-10 15:53:59

问题


I'm building a closed social network and currently when a user is not logged in they will always be redirected to the homepage of my domain.

What I would like to do is do the following:

  1. Use NGINX to check if a user is logged in (through checking for a cookie) and then when they go to the homepage (mydomain.com) redirect to to mydomain.com/newsfeed.

  2. This check should only be applied when a user brows to the homepage and should not work at ANY other url (or else they would always be redirected).

I'm very new to NGINX and looked at various tutorials for using cookies for redirect but failed to get an answer (most notably to limiting the redirect to only the homepage).

Thanks in advance!


回答1:


Final correct solution:

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



回答2:


Let's pretend I've a cookie like so: name=value

server {
    listen 80;
    server_name mydomain.com;

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

The location block will only match the homepage, check that the cookie exists (you could also just use if ($cookie_name)), and if present, redirect the user to http://example.com/newsfeed/



来源:https://stackoverflow.com/questions/29278910/nginx-redirect-a-user-based-on-cookie-for-a-specific-url-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!