4

I can't find many resources on how to manage cookies with Nginx…

I've seen that two variables are relatives to cookies, that is $http_cookies and $cookie_COOKIENAME.

Anyway, I absolutely don't know how to read a cookie with Nginx.

For exemple, i'd like to return a 403 if a cookie with a special value exists, i tried this but that doesn't seem to work :

if ($cookie_mycookiename = "509fd1e420bba") { return 403; }

also tried with $http_cookie

if ($http_cookie = "509fd1e420bba") { return 403; }

I really don't understand how Nginx handles cookies…

EDIT here is my full Nginx config

server {

listen 80;

root /home/minou/vids/;
index index.html index.htm;

#server_name localhost;


location / {

# First attempt to serve request as a file, then
# as directory, then fall back to index.html

try_files $uri $uri/ /index.html;

if ($cookie_fileURI = "6509fd1e420bba") { return 403; }
}

# anti hotlinking
location ~* \.(jpg)$ {
valid_referers none blocked mywebsite.com www.mywebsite.com;
if ($invalid_referer) { return 403; }

}

}
Buzut
  • 765
  • 3
  • 9
  • 23
  • Your 'if' statement seems correct. Maybe it is something else that is not working. Can you post your entire configuration? – Sudheer Dec 27 '12 at 14:00
  • my config file is quite simple, anyway, i've edited my post to add it. is there a way to check the value of either $http_cookie or $cookie_COOKIE as that might help ? – Buzut Dec 27 '12 at 14:18

2 Answers2

4

Please be aware that using if within a location might not work as expected, specially when used together with try_files. See: https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/

Please try this:

server {

    listen 80;

    root /home/minou/vids/;
    index index.html index.htm;

    #server_name localhost;

    if ($cookie_fileURI = "6509fd1e420bba") { return 403; }

    location / {
        # First attempt to serve request as file, then
        # as directory, then fall back to index.html

        try_files $uri $uri/ /index.html;
    }

    # anti hotlinking
    location ~* \.(jpg)$ {
        valid_referers none blocked mywebsite.com www.mywebsite.com;
        if ($invalid_referer) { return 403; }
    }

}
Patrick Mevzek
  • 9,273
  • 7
  • 29
  • 42
Ludwig
  • 401
  • 3
  • 9
1

Use below code:

if ($http_cookie ~* "cookiename=cookievalue") {return 403}
Andrew Schulman
  • 8,561
  • 21
  • 31
  • 47