首页 > 技术文章 > Nginx和Apache的防盗链

yghjava 2017-02-22 16:04 原文

How to protect your web resource not to steal

We will user Apache and Nginx to show how to do it.

 

1 Preparation environment

You should success configure Apache and Nginx in your OS and run web in it.

We will simulate one is normal web and another is larcenous web

 

IP

domain

function

192.168.229.128

bbs.etiantian.org

Normal web

192.168.229.128

www.etiantian.com

Larcenous web

 

We will put two pictures in bbs.etiantian.org/images/ one is resource picture and another is warning picture to tell larcenous web you steal my resource

 

If you input http://bbs.etiantian.org/images/res.png in your browser address, you will see following:

 

 

 

We will use it as the resource picture, and www.etiantian.com want to steal this resource in its web so he write following in the HTML

 

<span>This is larcenous web</span>

<img src="http://bbs.etiantian.org/images/res.png"/>

 

If we access http://www.etiantian.com/test.html we will find the  www.etiantian.com has success steal http://bbs.etiantian.org pictures resource

 

So how to protect bbs,etiantian.org resource

 

2 Solving Method

2.1 we can use HTTP referrer to solve this problem

2.1.1 Apache setting

We only set following settings is Apache bbs.etiantian.org in apache/conf/extra/http-vhost.conf

 

        

<VirtualHost *:80>

    ServerAdmin 948170910@qq.com

    DocumentRoot "/var/html/bbs"

    ServerName bbs.etiantian.org

    ErrorLog "logs/bbs-error_log"

    CustomLog "logs/bbs-access_log" common

    RewriteEngine On

    RewriteCond %{HTTP_REFERER} !http://bbs.etiantian.org/.*$ [NC]

    RewriteCond %{HTTP_REFERER} !^http://bbs.etiantian.org$ [NC]

    RewriteRule .*\.(gif|jpg|swf|png)$ http://bbs.etiantian.org/images/nolink.png [R,NC]

</VirtualHost>

 

So you will see flowing

 

 

 

The resource picture is forbidden access

 

We also see the html source code: The picture is also the resource, but www,etiantian.com do not access it. The setting is effective

 

 

<span>This is larcenous web</span>
<img src="http://bbs.etiantian.org/images/res.png"/>

 

 

 

2.1.2 Nginx settinga

We add following setting in bbs.etiantian.org in nginx/conf/extra/bbs.conf

 

location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$

 

        {

                valid_referers none blocked bbs.etiantian.org;

                if ($invalid_referer) {

 

                        rewrite ^/ http://bbs.etiantian.org/images/nolink.png;

 

 

                }

 

 

        }

 

So you will see

 

 

The resource picture will be steal by other web

 

 

 

3 Summary

So we can use REFERER in Apache and Nginx to protect your web, There some other method can solve this problems such as:

a):use cookie

b) use temporary web connection, it will no be give up in users finish access.

 

you can reference other doc to get how to use them

  

 

推荐阅读