nginx防盗链处理模块referer和secure_link模块

使用场景:某网站听过URI引用你的页面;当用户在网站点击url时;http头部会通过referer头部,将该网站当前页面的url带上,告诉服务本次请求是由这个页面发起的

思路:通过referer模块,用invalid_referer变量根据配置判断referer头部是否合法。

目的:拒绝非正常网站访问我们站点资源

默认:referer模块默认编译进nginx

指令介绍

Syntax: valid_referers none | blocked | server_names | string ...; #指定的域名地址 
Default: —
Context: server, location
Syntax: referer_hash_bucket_size size;  #希到内存里。内存的大写
Default: referer_hash_bucket_size 64; 
Context: server, location
Syntax: referer_hash_max_size size;
Default: referer_hash_max_size 2048; 
Context: server, location

valid_referers:参数

none:允许缺失的头部访问
block:允许referer没有对应值的请求
server_names:若referer站点域名与server_name中本机配的域名一样允许访问
表示域名及URI的字符串,对域名可在前缀或者后缀中含有*通配符:若头部值匹配字符串后则允许访问
正则表达式:若referer头部值匹配正则表达式后,允许访问
invalid_referer变量
允许访问时变量值为空
不允许访问时变量值为1
配置
server {
	server_name refere.com; 
	access_log  logs/refere.log  main;
	location /{
		valid_referers none blocked server_name
		*.taohui.pub www.taohui.org.cn/nginx/
		~.google.;
		if ($invalid_referer) {
		return 403;
		}
		return 200 "tars
";
	}
}

  测试

[root@python vhast]# curl -H 'referer: http://refere.com.cn/ttt' refere.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@python vhast]# curl -H 'referer:  http://www.taohui.pub/ttt' refere.com
tars
[root@python vhast]# curl -H 'referer: ' refere.com
tars
[root@python vhast]# curl -H '' refere.com
tars
[root@python vhast]# curl -H 'referer: http://www.taohui.tech' refere.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@python vhast]# curl -H 'referer: http://referer.taohui.tech' refere.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@python vhast]# curl -H 'referer: http://image.baidu.com/search/detail' refere.com
<html>
<head><title>403 Forbidden</title></head>
<body>
<center><h1>403 Forbidden</h1></center>
<hr><center>nginx/1.15.9</center>
</body>
</html>
[root@python vhast]# curl -H 'referer: http://image.google.com/search/detail' refere.com
tars

  

secure_link 模块介绍;默认未编译进去
通过验证URL中哈希值的方式防盗链
过程:由某服务器(也可以是nginx)生成加密后的安全rul,返回给客户端;客户端使用安全的uri访问,有nginx的secure_link变量是否通过
原理:哈希算法在技术上实现几乎是不可逆的;客户端只能拿到执行过哈希算法的uri;仅生产url的服务器、验证url是否安全的nginx这二者,才保存执行哈希算法钱的原始字符串;原始字符串通常由下列部分组成
1资源位置,如HTTP中指定资源的url,防止攻击者拿到一个安全url后可以任意访问资源
2用户信息,如用户的IP地址,限制其他用户盗用安全URL
3时间戳,使安全URL及时过期
4密钥,仅服务端有,增加攻击者猜测出原始字符串难度
变量:secure_link  、secure_link_expires
secure_link 指令介绍
 
Syntax: secure_link expression;   #值为空,不通过 为0 为过期 为1 通过
Default: —
Context: http, server, location
Syntax: secure_link_md5 expression; #怎么构造原始字符串
Default: —
Context: http, server, location
Syntax: secure_link_secret word;
Default: —
Context: location

  

 
 
 
草都可以从石头缝隙中长出来更可况你呢
原文地址:https://www.cnblogs.com/rdchenxi/p/11177842.html