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

时间:2021-10-17 13:15:02

一般,我们做好防盗链之后其他网站盗链的本站图片就会全部失效无法显示,但是您如果通过浏览器直接输入图片地址,仍然会显示图片,仍然可以右键图片另存为下载文件!依然可以下载?这样就不是彻底的防盗链了!

 [root@web01 vhosts]# cat default.conf
server {
listen default_server;
server_name 192.168.1.24 web01.espressos.cn *.qq.com *.baidu.com;
root /app/www;
index index.php index.html index.htm;
location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers none blocked *.espressos.cn;
if ($invalid_referer) {
rewrite ^/ http://192.168.1.25/404.jpg;
#return ;
}
}
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:;
fastcgi_index index.php;
include fastcgi.conf;
}
access_log /app/log/nginx/access/default.log;
}

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

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

首先当我输入我要打开的网址的时候,因为是直接输入的没有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的时候,才不会进行跳转。如下面实例:

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

[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>

接真输入图片地址可以显示图片:

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

 [root@web01 www]# cat /app/server/nginx/conf/vhosts/default.conf
server {
listen default_server;
server_name 192.168.1.24 web01.espressos.cn *.qq.com *.baidu.com;
root /app/www;
index index.php index.html index.htm;
location ~* \.(gif|jpg|png|swf|flv)$ {
valid_referers *.espressos.cn;
if ($invalid_referer) {
rewrite ^/ http://192.168.1.25/404.jpg;
#return ;
}
}
location ~ .*\.(php|php5)?$
{
#fastcgi_pass unix:/tmp/php-cgi.sock;
fastcgi_pass 127.0.0.1:;
fastcgi_index index.php;
include fastcgi.conf;
}
access_log /app/log/nginx/access/default.log;
}

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

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

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

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

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

   请确保server段中只有一个location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$,否则可能导致代码无效,如有这个代码段请合并或删除。
切记:如果要跳转到图片,记得替换的图片地址要使用没有防盗链的网站图片,否则由于替换的图片其实也处于防盗链情况下,会造成仍旧无法显示设置的图片。