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

15,699

Solution 1

Final correct solution:

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

Solution 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/

Share:
15,699
Bowe Frankema
Author by

Bowe Frankema

Updated on June 05, 2022

Comments

  • Bowe Frankema
    Bowe Frankema almost 2 years

    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!

  • Mendy
    Mendy over 5 years
    I wouldn't use 301 since its a permanent redirect, and the redirect you want is only for when logged in. rather use 302.
  • Matthew Haworth
    Matthew Haworth almost 4 years
    nginx.com/resources/wiki/start/topics/depth/ifisevil Don't use if in a location context
  • adriaan
    adriaan almost 4 years
    @MatthewHaworth don't just scream you can't use if inside the location context. The (only) 100% safe things which may be done inside if in a location context are: return ...; and rewrite ... last;. The above example uses return which is totally fine.
  • Ivan Shatsky
    Ivan Shatsky almost 3 years
    Exact match location = / { ... } will be faster than regex location ~ ^/$ { ... }
  • Armen Michaeli
    Armen Michaeli about 2 years
    Keep in mind that there is also the $cookie_*name* variable (looking at the use of $http_cookie in the answer).