资源盗链

资源盗链指的是此内容不在自己服务器上,而是通过技术手段,绕过别人的限制将别人的内容放到自己页面上最终展示给用户。以此来盗取大网站的空间和流量。简而言之就是用别人的东西成就自己的网站。

  • 案例
  1. 创建steal.html,页面引用两张图片 ```html

    郁金香

    上海鲜花港 - 郁金香

    百度CAR

    百度CAR
  1. 2. 配置Nginx服务
  2. ```nginx
  3. server{
  4. listen 80;
  5. server_name localhost;
  6. location /{
  7. root html;
  8. index steal.html;
  9. }
  10. }
  1. 访问http://172.41.100.15/

可以看出来,下面的图片地址添加了防止盗链的功能,上面的图片可以直接使用。
image.png

Nginx防盗链的实现原理

当浏览器向web服务器发送请求的时候,一般都会带上**Referer**,来告诉浏览器该网页是从哪个页面链接过来的,后台服务器可以根据获取到的这个**Referer**信息来判断是否为自己信任的网站地址,如果是则放行继续访问,如果不是则可以返回403(服务端拒绝访问)的状态信息。
image.png

  • 模拟盗链场景

Nginx防盗链 - 图5

  • Nginx防盗链的具体实现

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

语法 valid_referers none|blocked|server_names|string…
默认值
位置 server、location
  1. none: 如果Header中的Referer为空,允许访问
  2. blocked:在Header中的Referer不为空,但是该值被防火墙或代理进行伪装过,如不带”http://“ 、”https://"等协议头的资源允许访问。
  3. server_names:指定具体的域名或者IP
  4. string: 可以支持正则表达式和*的字符串。如果是正则表达式,需要以~开头表示
    • 案例
      1. location ~*\.(png|jpg|gif){
      2. valid_referers none blocked www.baidu.com 192.168.200.222 *.example.com example.* www.example.org ~\.google\.;
      3. if ($invalid_referer){
      4. return 403;
      5. }
      6. root /usr/local/nginx/html;
      7. }

      针对目录进行防盗链

      1. location /images {
      2. valid_referers none blocked www.baidu.com 192.168.200.222 *.example.com example.* www.example.org ~\.google\.;
      3. if ($invalid_referer){
      4. return 403;
      5. }
      6. root /usr/local/nginx/html;
      7. }
  • 安装第三方防盗链模块
  1. 下载nginx-accesskey源码

git clone ``[https://github.com.cnpmjs.org/darren2025/nginx-accesskey.git](https://github.com.cnpmjs.org/darren2025/nginx-accesskey.git)

  1. 升级Nginx

./configure --prefix=/home/nginx --with-http_gzip_static_module --with-http_gzip_static_module ``**--add-module**``=/home/nginx-accesskey
**--add-module****

  • 案例
  1. Nignx配置 ```nginx

    172.41.100.14 Nginx配置

    server{ listen 9088; server_name localhost; location /images { accesskey on; #功能开启 accesskey_hashmethod md5; #加密方式 accesskey_arg sign; #参数名称 accesskey_signature “mypass$remote_addr”; #参数 root /usr/local/nginx/html; } }

172.41.100.15 Nginx配置

server{ listen 80; server_name localhost; location /{ root html; index steal.html; } }

  1. 2. steal.htm配置
  2. ```html
  3. <html>
  4. <head>
  5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  6. </head>
  7. <body>
  8. <h1>172.41.100.14</h1>
  9. <img src="http://172.41.100.14:9088/images/1.jpg" alt="tom" />
  10. </body>
  11. </html>
  1. 访问172.41.100.15

image.png

  1. 直接访问172.41.100.14

image.png

  1. 按照172.41.100.14的配置规则传递参数

参数名称为sign,参数值为mypass+客户端ip生成md5加密串
image.png

  1. 带参数访问效果

image.png