Nginx – checking and reading cookies with nginx

http-cookienginx

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

}

}

Best Answer

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

}