您的位置:首页 > 运维架构 > Nginx

Linux Centos7下实现nginx防盗链部署

2019-09-08 15:47 1861 查看

一、原理:

nginx 防止网站资源被盗用模块

ngx_http_referer_module

​ HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况.

二、防盗链配置

[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"';

三、配置原服务器

准备两台机器,一张图片
1、在网站发布目录下编辑html文件并准备一张图片名为33.jpg,这里网站发布目录为/web1

vim /web1/index.html
<html>
<head>
<meta charset="utf-8">
<title>hostphoto.com</title>
</head>
<body>
<center><img src="33.jpg" alt="fangxi" width="1000px" height="900px" /></center>
</body>
</html>

2、编辑nginx子配置文件

location / {
root   /web1;
index  index.html index.htm;
valid_referers none blocked 192.168.16.150;
if ($invalid_referer) {
return 403;
}
}

• none : 允许没有http_refer的请求访问资源;
• blocked : 允许不是http://开头的,不带协议的请求访问资源---被防火墙过滤掉的;
• server_names : 只允许指定ip/域名来的请求访问资源(白名单);

3、检查配置文件是否有错误,没有错误重新加载。

nginx -t

nginx -s reload

四、配置要盗用的服务器

1、配置nginx访问页面并创建目录

location / {
root   /web1;
index  index.html index.htm;
}
mkdir /web1

2、创建页面

vim /web1/index.html
<html>
<body style="background-color:red;">
<img src="http://192.168.16.150/33.jpg" />
</body>
</html>

五、测试

当开启防盗链时,访问要盗用的服务器,图片显示不出来。

当把防盗链代码注释之后,访问要盗用的服务器,图片就可以显示出来。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: