65 Nginx防盗链的实现原理和实现步骤

65 Nginx防盗链的实现原理和实现步骤

65.1 实现原理原理

浏览器向web服务器发送请求时,服务器返回时一般都会带上Referer,用以通知浏览器该网页源于哪个页面链接

1581769079083

浏览器访问:https://www.doubao.com/

image

后台服务器可以根据获取到的 Referer 信息判断,是否信任此网站地址,如果信任,则放行继续访问,如果不信任,则返回 403 码(服务端拒绝访问)

65.2 盗链

[root@nginx-100 /usr/local/nginx]# cat conf/nginx.conf
user www;
worker_processes 2;
error_log logs/error.log;
pid logs/nginx.pid;
#daemon on; # 默认on
events {
    accept_mutex on;
    multi_accept on;
    worker_connections  1024;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout  65;
    include nginx_gzip.conf;

    # 模拟服务器a
    server {
        listen       80;
        server_name  localhost;
                
        location / {
          root html;
          index index.html index.htm;
        }
    }  
   # 模拟服务器b
    server {
        listen       8080;
        server_name  localhost;

        location ~ .*\.(png|jpg|gif)$ {
           root html/;
        }

        location /getUser {
           add_header Access-Control-Allow-Origin http://10.0.0.100;
       add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
           default_type application/json;
           return 200 '{"id":1,"name":"TOM","age":18}';
        }

        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            root   html;
        }
    }  
}
[root@nginx-100 /usr/local/nginx]# nginx -t && nginx -s reload
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx-100 /usr/local/nginx]# cat html/a.html 
<html>
  <head>
        <meta charset="utf-8">
        <title>跨域问题演示</title>
        <script src="jquery.js"></script>
        <script>
            $(function(){
                $("#btn").click(function(){
                        $.get('http://10.0.0.100:8080/getUser',function(data){
                                alert(JSON.stringify(data));
                        });
                });
            });
        </script>
  </head>
  <body>
        <input type="button" value="获取数据" id="btn"/>
        <!-- 京东 -->
        <img src="https://img14.360buyimg.com/n7/jfs/t1/101062/37/2153/254169/5dcbd410E6d10ba22/4ddbd212be225fcd.jpg"/><br/>
        <!-- 百度 -->
        <img src="https://pics7.baidu.com/feed/cf1b9d16fdfaaf516f7e2011a7cda1e8f11f7a1a.jpeg?token=551979a23a0995e5e5279b8fa1a48b34&s=BD385394D2E963072FD48543030030BB"/><br/>
        <!-- Test图片 -->
        <img src="http://10.0.0.100:8080/images/jj.png"/>
  </body>
</html>
[root@nginx-100 /usr/local/nginx]# tree html/
html/
├── 50x.html
├── a.html
├── images
│   └── jj.png
├── index.html
├── jquery.js
└── welcome.html

1 directory, 6 files

浏览器访问:http://10.0.0.100:8080/images/jj.png

image

演示盗链:浏览器访问:http://10.0.0.100/a.html ,80端口的网站,盗取了8080端口网站的信息

image

65.3 valid_referers

valid_referers:通过查看 referer 自动和 valid_referers 后面的内容进行匹配,如果匹配到了,就将 $invalid_referer 变量置为 0,如果没有匹配到,则将  $invalid_referer 变量置为 1,匹配过程中不区分大小写

语法 valid_referers none | blocked | server_names | string ...
默认值 _
位置 server 、location

 

 

 

 

none:Header 中的 Referer 为空,允许访问

blocked:Header 中的 Referer 不为空,但该值被防火墙或代理进行伪装过,如不带 "http://"、"https://" 等协议头的资源允许访问

server_names:指定具体的域名或 IP 允许访问

string:支持正则表达式或 * 的字符串,如果是正则表达式,需要以 ~ 开头表示

65.4 演示防盗链

[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf
user www;
worker_processes 2;
error_log logs/error.log;
pid logs/nginx.pid;
#daemon on; # 默认on
events {
    accept_mutex on;
    multi_accept on;
    worker_connections  1024;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout  65;
    include nginx_gzip.conf;

    # 模拟服务器a
    server {
        listen       80;
        server_name  localhost;
                
        location / {
          root html;
          index index.html index.htm;
        }
    }  
   # 模拟服务器b
    server {
        listen       8080;
        server_name  localhost;

        location ~ .*\.(png|jpg|gif)$ {
           valid_referers none blocked www.baidu.com;
           if ($invalid_referer){
              return 403;
           }
           root html/;
        }

        location /getUser {
           add_header Access-Control-Allow-Origin http://10.0.0.100;
       add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
           default_type application/json;
           return 200 '{"id":1,"name":"TOM","age":18}';
        }

        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            root   html;
        }
    }  
}
[root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful

浏览器访问:http://10.0.0.100:8080/images/jj.png,原访问不受影响

image

浏览器访问:http://10.0.0.100/a.html,盗链图片被禁用

image

image

注意:只能对图片做防盗链,如何批量防盗链?

65.5 目录防盗链

[root@nginx-100 /usr/local/nginx/conf]# cat nginx.conf
user www;
worker_processes 2;
error_log logs/error.log;
pid logs/nginx.pid;
#daemon on; # 默认on
events {
    accept_mutex on;
    multi_accept on;
    worker_connections  1024;
    use epoll;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout  65;
    include nginx_gzip.conf;

    # 模拟服务器a
    server {
        listen       80;
        server_name  localhost;
                
        location / {
          root html;
          index index.html index.htm;
        }
    }  
   # 模拟服务器b
    server {
        listen       8080;
        server_name  localhost;

        location ~ /images/.*\.(png|jpg|gif)$ {
           valid_referers none blocked www.baidu.com;
           if ($invalid_referer){
              return 403;
           }
           root html/;
        }

        location /getUser {
           add_header Access-Control-Allow-Origin http://10.0.0.100;
       add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE;
           default_type application/json;
           return 200 '{"id":1,"name":"TOM","age":18}';
        }

        error_page   500 502 503 504 404 /50x.html;
        location = /50x.html {
            root   html;
        }
    }  
}
[root@nginx-100 /usr/local/nginx/conf]# nginx -t && nginx -s reload
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@nginx-100 /usr/local/nginx/conf]# cat ../html/a.html 
<html>
  <head>
        <meta charset="utf-8">
        <title>跨域问题演示</title>
        <script src="jquery.js"></script>
        <script>
            $(function(){
                $("#btn").click(function(){
                        $.get('http://10.0.0.100:8080/getUser',function(data){
                                alert(JSON.stringify(data));
                        });
                });
            });
        </script>
  </head>
  <body>
        <input type="button" value="获取数据" id="btn"/>
        <!-- 京东 -->
        <img src="https://img14.360buyimg.com/n7/jfs/t1/101062/37/2153/254169/5dcbd410E6d10ba22/4ddbd212be225fcd.jpg"/><br/>
        <!-- 百度 -->
        <img src="https://pics7.baidu.com/feed/cf1b9d16fdfaaf516f7e2011a7cda1e8f11f7a1a.jpeg?token=551979a23a0995e5e5279b8fa1a48b34&s=BD385394D2E963072FD48543030030BB"/><br/>
        <!-- Test图片 -->
        <img src="http://10.0.0.100:8080/images/jj.png"/>
        <img src="http://10.0.0.100:8080/images/mv.png"/>
  </body>
</html>
View Code

浏览器访问:http://10.0.0.100:8080/images/jj.png

image

浏览器访问:http://10.0.0.100:8080/images/mv.png

image

浏览器访问:http://10.0.0.100/a.html ,整个 images 目录下的图片都被禁止盗链

image

 

问题:Referer的限制比较粗,随意加一个Referer,将无法进行限制

此处通过Nginx的第三方模块 ngx_http_accesskey_module 可以实现防盗链,后面Nginx的模块篇进行详细的讲解

 

———————————————————————————————————————————————————————————————————————————

                                                                                                                         无敌小马爱学习

posted on 2026-05-19 12:17  马俊南  阅读(8)  评论(0)    收藏  举报