checking and reading cookies with nginx
Solution 1
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; }
}
}
Solution 2
Use below code:
if ($http_cookie ~* "cookiename=cookievalue") {return 403}
Related videos on Youtube
![Buzut](https://i.stack.imgur.com/SWDAg.png?s=256&g=1)
Buzut
Internaute de l'Internet Passionate about all things digital I make things with #JavaScript #NodeJS #vueJS & #Linux
Updated on September 18, 2022Comments
-
Buzut almost 2 years
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 over 11 yearsmy 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 ?
-