A
A
Alex2019-11-04 19:02:12
Nginx
Alex, 2019-11-04 19:02:12

How to properly use valid_referers in Nginx?

I decided to try to make protection from hotlink. The solution came out immediately:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    				valid_referers none blocked my.domain.ru www.my.domain.ru;
            if ($invalid_referer) {
                return   403;
            }
                expires max;
                log_not_found off;
    }

However, nothing changed after nginx -s reload. I tried to insert an image in the codepen and jsfiddle - everything works and is not blocked.
I decided to check the operation of the section in general and change the domain to the left one, all the listed files immediately went to 403, i.e. if you change the domain everything is fine. However, if you put your own, then inserting a picture into jsfiddle and codepen is all right.
Then I looked at the NGINX docs, it says $invalid_referer An empty string if the value of the “Referer” field of the request header is considered correct, otherwise “1”.
I tried to change it to if ($invalid_referer = "1") { , no result either.
Could you please explain how it actually works?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex, 2019-11-05
@alexjet73

I found a solution, on one site in the comments. And it worked for me.
Remove none in the line valid_referers none blocked my.domain.ru www.my.domain.ru;
I would be grateful if someone could tell me the reason why it didn't work with none. Indeed, in the NGINX docs, an example is written with none (as a parameter for the absence of a Referer)?!

B
Bahadir Ishmatov, 2020-10-26
@bahinnn

I will write for those who have the same problems as the topic starter

valid_referers none blocked server_names ~(\.yandex\.|\.google\.);
if ($invalid_referer) {
rewrite (.*)\.(jpg|jpeg|png|gif)$ [ссылка куда редиректить];
или
return 403; //блокируем 
}

if you need to block access to the url on your site, except for the necessary referer:
location ~ "[ссылка на вашем сайте]" {
try_files $uri $uri/ /index.php?$args;
valid_referers none blocked server_names ~(\.yandex\.|\.google\.);
if ($invalid_referer) { return 403;  }
}

clarification:
server_names is your domain, you don't need to enter something like my.domain.com
if you remove [none blocked] these = ~(\.yandex\.|\.google\.) block (topic author has no external sources , so [none blocked] interfered)
you need to add to the location following the sequence - insert it into the wrong location, it will not work!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question