今天来讲下NGINX的防盗链,应该说只要是静态资源都是可以防盗链的,只需要在Server字段加上几行代码即可。众所周知网站出名了后,会有各种刁民来找茬的,最常见的就是爬你网站的东西。
关于防盗链这里不得不提一下网页的加载顺序是先加载HTML相关的内容,然后解析HTML的内容,那些需要加载图片,那些需要加载文件,是逐步加载的,所以可以在加载静态资源的时候做防盗链的操作,例如:在加载图片的时候直接跳转去其他链接,或者直接返回404,403等错误代码,拒绝它的请求。
server {
listen 80;
server_name git.ascoo.com;
root "E:\mmogatrade";
location / {
index index.html index.htm index.php;
#autoindex on;
if (!-e $request_filename){
rewrite ^/(.*)$ /index.php/$1 last;
}
}
#防盗链设置
location ~ .*\.(gif|jpg|jepg|png|PNG|bmp|flv|wma|wmv|swf|mp3|zip|rar|torrent)$ {
expires 1d;
valid_referers none blocked *.ascoo.de *.ascoo.co *.ascoo.com localhost;
if ($invalid_referer)
{
#rewrite跳转到那张图片,也可以直接return错误代码
rewrite ^/ http://www.buruyouni.com/static/admin/dist/img/user7-128x128.jpg;
#return 404;
}
}
location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
valid_referers 字段是允许那些域名访问。
需要注意的是:图片等静态文件有一天的缓存,expires 1d;测试的时候可以用强刷方式测试,更改完配置重启NGINX即可。
还有如果直接通过文件方式访问,如file:///C:/Users/26975/Desktop/a.html,防盗链是没有用的