nginx USES the referer directive to achieve anti hotlinking configuration

  • 2020-06-07 05:41:22
  • OfStack

Realize image anti-hotlinking:


location ~* \.(gif|jpg|png|webp)$ {
   valid_referers none blocked domain.com *.domain.com server_names ~\.google\. ~\.baidu\.;
   if ($invalid_referer) {
    return 403;
    #rewrite ^/ http://www.domain.com/403.jpg;
   }
   root /opt/www/image;
  }

Above all from domain com and domain name as well as baidu and google site can access to the current site of the pictures, if the source domain is not in the list, then $invalid_referer is equal to 1, in if statement returns a 403 to the user, so that the user will see a 403 page, if you use the following rewrite, and hotlinking images will show 403. jpg. The none rule allows empty referer access, that is, when the image is opened directly in the browser and referer is empty, the image will still display normally.


[root@loya ~]# curl -I http://qingkang.me/1.jpg -H 'Referer:http://www.baidu.com'
HTTP/1.1 200 OK
Server: nginx/1.8.1
Date: Fri, 16 Dec 2016 14:56:51 GMT
Content-Type: image/jpeg
Content-Length: 17746
Last-Modified: Tue, 16 Aug 2016 03:20:21 GMT
Connection: keep-alive
ETag: "57b28675-4552"
Accept-Ranges: bytes
[root@loya ~]# curl -I http://qingkang.me/1.jpg -H 'Referer:http://www.qq.com'
HTTP/1.1 403 Forbidden
Server: nginx/1.8.1
Date: Fri, 16 Dec 2016 14:56:58 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 168
Connection: keep-alive

instruction

valid_referers none | blocked | server_names | string... ;

Configuration section: server, location

Specifies the valid source 'referer', which determines the value of the built-in variable $invalid_referer. If the referer header is included in the valid url, this variable is set to 0, otherwise it is set to 1.

Parameter description:

none "Referer" is empty blocked "Referer" is not empty, but the value inside has been removed by the agent or firewall. These values do not begin with http:// or https://, but with the form "Referer: XXXXXXX" server_names "Referer" source header contains current server_names (current domain name) arbitrary string any string that defines the server name or optional URI prefix. Host names can begin or end with an *, and host ports in the source domain are ignored during source header detection regular expression regular expression,~ to exclude the string beginning https:// or http://.

Pay attention to

By Referer to prevent hotlinking compared to the basic, only simple way to achieve the theft of resources. The request to construct Referer is easy to implement.

conclusion

The above is the whole content of this article, I hope the content of this article can bring 1 definite help to your study or work, if you have any questions, you can leave a message to communicate.


Related articles: