欢迎光临
我们一直在努力

Linux Centos7下实现nginx防盗链部署

一、原理:

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 >
    <img src="https://cache.yisu.com/upload/information/20200309/28/29438.jpg" />
</body>
</html>

五、测试

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

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

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。