use strict;
use lib qw(d:/ProgramFiles/ApacheSoftwareFoundation/Apache2.2/modperl); # 把这个路径加入到perl lib路径
#d:/ProgramFiles/ApacheSoftwareFoundation/Apache2.2 这部分替换成实际的目录
use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Connection ();
use Apache2::RequestUtil ();
use Apache2::ServerUtil ();
use Apache2::Log ();
use Apache2::Request ();
1;
KeyAccess.pm
package KeyAccess;
use strict;
use Apache2::RequestRec ();
use Apache2::RequestIO ();
use Apache2::Connection ();
use Apache2::RequestUtil ();
use Apache2::ServerUtil ();
use Apache2::Log ();
use Apache2::Const -compile => qw(OK FORBIDDEN);
use Apache2::Request ();
use Digest::MD5 qw(md5 md5_hex md5_base64);
sub handler {
my $r = shift;
my $req = Apache2::Request->new($r);
my $ip = $r->connection->remote_ip;
my $k = $req->param('key') || ''; # 判断访问时是否带key参数
my $key = $r->dir_config('key') || '123'; # 加载httpd.conf配置中的key值
my $md5value=md5_hex($key.$ip); #使用MD5加密验证
if ($md5value eq $k) { # 相等可以正常访问
return Apache2::Const::OK;
} else { # 否则显示拒绝访问
my $s = Apache2::ServerUtil->server;
$s->log_error("[$ip--------forbidden.]");
return Apache2::Const::FORBIDDEN;
}
}
1;
6.启动服务器
7.尝试访问http://host:port/index.html,会返回一个forbidden响应.
只有使用http://host:port/index.html?key=value才能访问,这里的value为httpd.conf中设置的key+用户ip的MD5值.
总结:
自己写的应用需要按照这个约定返回给用户带有正确key的链接地址,用户点击之后正常访问资源.而且该链接只针对一个ip的用户,copy给其它ip的用户是没用的.这样就达到了防盗链的目的.
Perl脚本的验证部分也可以写别的东西做验证,比如验证加密的时间串,实现自定义过期时间的链接.
本文只是照本宣科,并未追根溯源,mod_perl可以访问很多Apache的api,可以深入研究.
此外我也不知道为什么要安装libapreq2,但目的达成,暂时足矣.
整个过程,还稍稍学习了一下Perl脚本,收获蛮大的.