Nginx - How do I know when $http_referer is not set or empty?
Asked Answered
P

3

5

How do I know when the nginx variable $http_referer is not set or empty?

I receive some requests that don't have a http referer. In nginx logs $http_referer appears like that: "-". What I am trying to do is to "return 403;" if the $http_referer is not set or empty as in this case.

Thanks!

Pallor answered 3/5, 2011 at 9:23 Comment(3)
I tried using regular expressions but seems not to be working - or rejects everything with 403. I searched for a method that would tell me if a nginx variable is set or not.... but I didn't find it yet.Pallor
What if my browser is configured to never send referer headers for any site?Trainer
Hmm... what I really need is to deny every acces to resources of the requests that are plain GETs for example and they don't have 'anyone' sending them... such as http_referer...Pallor
U
11

http://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers

valid_referers server_names ~.;
if ($invalid_referer) {
    return   403;
}
Unmitigated answered 3/5, 2011 at 9:31 Comment(3)
Thanks.. but I got an error: '[emerg]: the "none" or "blocked" referers are specified in the "valid_referers" directive without any valid referer'Pallor
@Clawsy Fixed version blocks every request with empty referer. Any non-empty referer considered correct.Unmitigated
server_names ~. works as opposed to valid_referers none; which throws the error @Clawsy mentions. @Tim's working technique sets the list of valid server_names to match any server by setting it to a regular expression using ~ and any character using . . See also : nginx.org/en/docs/http/ngx_http_referer_module.htmlCrosswise
H
1

How about this?

if ($http_referer ~ /^$/) {
    return 403;
}
Homoiousian answered 29/12, 2016 at 21:59 Comment(0)
W
1

It works for me, likes below:

set $flag 0;
if ($http_referer = "-") {
    set $flag 1;
}
if ($flag = 1) {
    return 403;
}
Wigwag answered 26/2, 2020 at 10:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.