Nginx an implementation method that sets Referer to prevent map theft

  • 2020-05-17 07:36:44
  • OfStack

If the image of the server is hotlinking by other websites, it will affect the bandwidth and access speed of the server, then we need to set the image file or video file anti-hotlinking function;

Anti-hotlinking function, in simple terms, you can directly access the resource, but can not put my resource links on your own server for others to access, especially the picture or video this relatively large file, easy to cause the server response is slow.

If it is not a picture bed, also really afraid of other sites directly use site pictures. This flow is likely to be wiped out immediately, after all, CDN was bought for nothing. So, set a hotlinking guard and Nginx will do the trick.

1 generally speaking, browsers implemented under the HTTP protocol bring the URL of the current site with them when visiting the B site from the A site to indicate where the click originated. Therefore, the module of Nginx also relies on this to implement, so if the hacker does not add this head, there is still no pleasant anti-theft graph.

The official website of Nginx is as follows:

[

Syntax: valid_referers none | blocked | server_names | string ...;
Default: -
Context: server, location

]

Introduction to the nginx referer directive

Source ngx_http_referer_module nginx module is often used to stop illegal domain name request. We should bear in mind that camouflage Referer head is very simple thing, so this module can only be used to prevent most illegal request. We should keep in mind that some legal request will not take referer source head, so sometimes don't refuse to source (referer) for the request of the empty head.

Therefore, we can add the code in the server or location block, which I saved as valid_referers.conf:


valid_referers none blocked server_names;

if ($invalid_referer) {
 return 403;
}

Then add include /etc/nginx/ valid_referers.conf where it is needed. Of course, this can only be done if valid_referers.conf is placed in the etc/nginx/ valid_referers.conf path on the corresponding machine.

Example:


 location /articles/img {
  include /etc/nginx/valid_referers.conf;
  root /data/blog/code;
 }

Related articles: