完美的nginx图片防盗链设置详解

 

通常,咱们作好防盗链以后其余网站盗链的本站图片就会所有失效没法显示,可是您若是经过浏览器直接输入图片地址,仍然会显示图片,仍然能够右键图片另存为下载文件!依然能够下载?这样就不是完全的防盗链了!php

 1 [root@web01 vhosts]# cat default.conf
 2 server {
 3     listen 80 default_server;
 4     server_name 192.168.1.24 web01.espressos.cn *.qq.com *.baidu.com;
 5     root /app/www;
 6     index index.php index.html index.htm;
 7     location ~* \.(gif|jpg|png|swf|flv)$ {
 8     valid_referers none blocked *.espressos.cn;
 9     if ($invalid_referer) {
10         rewrite ^/ http://192.168.1.25/404.jpg;
11         #return 404;
12         }
13     }
14     location ~ .*\.(php|php5)?$
15     {
16        #fastcgi_pass  unix:/tmp/php-cgi.sock;
17         fastcgi_pass  127.0.0.1:9000;
18     fastcgi_index index.php;
19     include fastcgi.conf;
20     }
21     access_log  /app/log/nginx/access/default.log;
22 }

注意第8行 “valid_referers none blocked" 其中"none" "blocked" 的意思分别是:html

none表明没有referer;blocded表明有referer可是被防火墙或者是代理给去除了。nginx

首先当我输入我要打开的网址的时候,由于是直接输入的没有referer因此匹配了
valid_referers后面的none或者是blocked 因此invalid_referer值为0 因此不进行跳转.
当我是从这个网站里面的连接跳到该网站首页的时候 由于referer的值是确定包含srever_names 因此匹配了server_names因此不进行跳转。
当我从搜素引擎进去的时候由于referer字段相似于www.google.com.hk/search
开始进行匹配 发现没有一个匹配,则此时会设置invalid_referer值为1 if语句成功执行,进行了跳转. 达到功能

若是把这两个(none,blocked)去掉就能够真正的实现防盗连了!由于只有匹配到server_name的时候,才不会进行跳转。以下面实例:web

[root@web01 www]# cat index.html 
<html>
<body>
<h1>hello world bass!! </h1>
<img alt="bass.png" src="/bass.png" height="auto" width="auto"></img>
</body>
</html>

接真输入图片地址能够显示图片:浏览器

 1 [root@web01 www]# cat /app/server/nginx/conf/vhosts/default.conf
 2 server {
 3     listen 80 default_server;
 4     server_name 192.168.1.24 web01.espressos.cn *.qq.com *.baidu.com;
 5     root /app/www;
 6     index index.php index.html index.htm;
 7     location ~* \.(gif|jpg|png|swf|flv)$ {
 8     valid_referers *.espressos.cn;
 9     if ($invalid_referer) {
10         rewrite ^/ http://192.168.1.25/404.jpg;
11         #return 404;
12         }
13     }
14     location ~ .*\.(php|php5)?$
15     {
16        #fastcgi_pass  unix:/tmp/php-cgi.sock;
17         fastcgi_pass  127.0.0.1:9000;
18     fastcgi_index index.php;
19     include fastcgi.conf;
20     }
21     access_log  /app/log/nginx/access/default.log;
22 }

注意第8号:8 valid_referers *.espressos.cn;去掉了none,blocked:(效果以下)app

当再次输入web01.espressos.cn/bass.png时发生跳转到192.168.1.25/404.jpg:网站

这才实现了完美的防盗链!!google

   请确保server段中只有一个location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$,不然可能致使代码无效,若有这个代码段请合并或删除。
    切记:若是要跳转到图片,记得替换的图片地址要使用没有防盗链的网站图片,不然因为替换的图片其实也处于防盗链状况下,会形成仍旧没法显示设置的图片。
相关文章
相关标签/搜索