之前写过一篇blog是《利用lighttpd的mod_secdownload实现防盗链》,最近看到nginx也有类似功能,叫secure_link_module模块也试验了一把。
nginx需要打一个补丁才能实现跟lighttpd一样,通过时间戳来控制url过期。
1.给nginx打补丁,下载《nginx-secure-link-ttl》:
cd nginx-0.7.62
patch -p1 < ../nginx-secure-link-ttl.patch2.编译nginx的时候加上“-with-http_secure_link_module”
3.配置nginx:
location /down/ {
secure_link_secret "sbear.cn"; //密钥
secure_link_ttl on;
root /data/test/down;
if ($secure_link = "") {
return 403;
}
rewrite ^ /$secure_link break;
}4.php demo:
<?php
define(URL_TIMEOUT, 3600); //这里设置过期时间单位是秒
$prefix = "http://www.sbear.cn/down";
$protected_resource = "test.exe";
$secret = "sbear.cn"; //密钥
$time = pack('N', time() + URL_TIMEOUT);
$timeout = bin2hex($time);
$hashmac = md5( $protected_resource . $time . $secret );
$url = $prefix . "/" . $hashmac . $timeout . "/" . $protected_resource;
echo "<a href=" . $url . ">down</a>";
echo time();
?>