两个网站 A 和 B, A网站引用了B网站上的图片,这种行为就叫做盗链。 防盗链,就是要防止A引用B的图片。
1、nginx 防止网站资源被盗用模块
ngx_http_referer_module
防盗链配置
配置要点 :
[root@nginx-server ~]# vim /etc/nginx/nginx.conf
# 日志格式添加"$http_referer"
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
# valid_referers 使用方式
Syntax: valid_referers none | blocked | server_names | string ...;
Default: —
Context: server, location
-
none : 允许没有http_refer的请求访问资源;
-
blocked : 允许不是http://开头的,不带协议的请求访问资源;
-
server_names : 只允许指定ip/域名来的请求访问资源(白名单);
准备两台机器,两张图片(缓存问题)
[root@project3 conf.d]# vim b.conf
server {
listen 80;
location / {
root /opt/www;
index index.html;
valid_referers none blocked *.qf.com 10.11.67.86; #添加了none blocked 两个模块
if ($invalid_referer) { #白名单:.qf.com 和10.11.67.86 链接本机的网站
return 403;
}
}
location ~ .*\.(gif|jpg|png|jpeg)$ { #~正则匹配格式,. 一个字符 * 一个或多个字符 (gif|jpg)gif或jpg格式文件,$以之前结尾
root /opt/www;
valid_referers none qf.com 10.11.67.86 ; #同上,不添加none模块,则不允许用户用浏览器(浏览器没有http_refer)访问目录下的图片,只能通过有http_refer的访问
#(说人话):浏览器测试需要添加none,curl测试不用添加
if ($invalid_referer) {
return 403;
}
}
}
===============================================================================
重载nginx服务
[root@nginx-server ~]# nginx -s reload -c /etc/nginx/nginx.conf
第二台机器客户端
配置nginx访问页面
创建页面
[root@project2 doc]# vim index.html
<html>
<head>
<meta charset="utf-8">
<title>qf.com</title>
</head>
<body style="background-color:black;"> #页面背景颜色
<img src="http://10.11.67.19/test.jpg"/> #盗链接的网页
</body>
</html>
======================================================================
浏览器测试为自带http_refer
测试不带http_refer:
[root@project1 ~]# curl -e http://www.qf.com -I "http://10.11.67.19/"
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Mon, 12 Oct 2020 12:34:21 GMT
Content-Type: text/html
Content-Length: 40
Last-Modified: Mon, 12 Oct 2020 08:01:45 GMT
Connection: keep-alive
ETag: "5f840d69-28"
Accept-Ranges: bytes
测试带非法http_refer:
[root@project1 ~]# curl -e http://www.ss.com -I "http://10.11.67.19/"
HTTP/1.1 402 Payment Required
Server: nginx/1.18.0
Date: Mon, 12 Oct 2020 12:34:28 GMT
Content-Type: text/html
Content-Length: 167
Connection: keep-alive
测试带合法的http_refer:
通过允许盗链接的ip(ip-86)访问真实的服务器(ip-19)
[root@project1 ~]# curl -e http://10.11.67.86 -I "http://10.11.67.19/"
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Mon, 12 Oct 2020 12:36:17 GMT
Content-Type: text/html
Content-Length: 40
Last-Modified: Mon, 12 Oct 2020 08:01:45 GMT
Connection: keep-alive
ETag: "5f840d69-28"
Accept-Ranges: bytes
[root@project1 ~]# curl -e http://10.11.67.86 -I "http://10.11.67.19/test.jpg"
HTTP/1.1 200 OK
Server: nginx/1.18.0
Date: Mon, 12 Oct 2020 12:36:36 GMT
Content-Type: image/jpeg
Content-Length: 636636
Last-Modified: Mon, 12 Oct 2020 07:38:09 GMT
Connection: keep-alive
ETag: "5f8407e1-9b6dc"
Accept-Ranges: bytes