Nginx-防盗链

2022/1/23 7:04:15

本文主要是介绍Nginx-防盗链,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

官网:http://nginx.org/en/docs/http/ngx_http_referer_module.html

$http_referer   #url跳转来源,用来记录从那个页面链接访问过来的

 防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗链,referer就是之前的那个网站域名,正常的referer信息有以下几种:

none:请求报文首部没有referer首部,比如用户直接在浏览器输入域名访问web网站,就没有referer信息。
blocked:请求报文有referer首部,但无有效值,比如为空。
server_names:referer首部中包含本主机名及即nginx 监听的server_name。
arbitrary_string:自定义指定字符串,但可使用*作通配符。
regular expression:被指定的正则表达式模式匹配到的字符串,要使用~开头,例如: ~.*\.magedu\.com。

正常通过搜索引擎搜索web 网站并访问该网站的referer信息如下:

{"@timestamp":"2019-02-
28T13:58:46+08:00","host":"192.168.7.102","clientip":"192.168.0.1","siz
e":0,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-
","http_host":"www.magedu.net","uri":"/index.html","domain":"www.magedu.net","xff":"-
","referer":"https://www.baidu.com/s?ie=utf-
8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=www.magedu.net&oq=www.mageedu.net&rsv_pq=d63060680
002eb69&rsv_t=de01TWnmyTdcJqph7SfI1hXgXLJxSSfUPcQ3QkWdJk%2FLNrN95ih3XOhbRs4&rqlang=cn&r
sv_enter=1&inputT=321&rsv_sug3=41&rsv_sug2=0&rsv_sug4=1626","tcp_xff":"","http_user_age
nt":"Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/72.0.3626.119 Safari/537.36","status":"304"}

 如何实现web盗链

[root@s2 conf.d]# pwd
/apps/nginx/conf/conf.d

[root@s2 conf.d]# cat mageedu.net.conf
server {
  listen 80;
  server_name www.mageedu.net;   //盗链方

  location / {
    index index.html;
    root "/data/nginx/html/mageedu";
    access_log /apps/nginx/logs/www.mageedu.net.log access_json;
  }
}

#准备盗链web页面:
[root@s2 conf.d]# mkdir /data/nginx/html/mageedu
[root@s2 conf.d]# cat /data/nginx/html/mageedu/index.html
<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>盗链页面</title>
</head>
<body>
<a href="http://www.magedu.net">测试盗链</a>
<img src="http://www.magedu.net/images/1.jpg">  //被盗链方
</body>
</html>

 重启Nginx并访问http://www.mageedu.net/可以正常显示http://www.magedu.net/images/1.jpg网站内容

 验证两个域名的日志,是否会在被盗连的web站点的日志中出现以下盗链日志信息:

 

基于访问安全考虑,nginx支持通过ungx_http_referer_module模块 https://nginx.org/en/docs/http/ngx_http_referer_module.html#valid_referers 检查访问请求的referer信息是否有效实现防盗链功能,定义方式如下:

  location  /images {
     root /data/nginx/html/pc;
     index index.html;
     valid_referers none blocked server_names
         *.example.com example.* www.example.org/galleries/
         ~\.google\.;
    
    if ($invalid_referer) {
       return 403;
  }
location ^~ /images {
  root /data/nginx;
  index index.html;
  valid_referers none blocked server_names *.magedu.com www.magedu.* 
      api.online.test/v1/hostlist  ~\.google\. ~\.baidu\.;  #定义有效的referer
  if ($invalid_referer) {  #假如是使用其他的无效的referer访问:
    return 403; #返回状态码403
  }
}

 使用浏览器访问盗链网站 www.mageedu.net, 验证是否提前状态码403:

 

 

 其他参考文章:https://support.huaweicloud.com/usermanual-vod/vod010013.html

 



这篇关于Nginx-防盗链的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程