welcome to xlongwei.com

欢迎大家一起学习、交流、分享


QQ群:162333776 邮箱:admin@xlongwei.com

nginx安全下载模块ngx_http_secure_link_module


分类 Java   关键字 分享   标签 linux   nginx   发布 admin  1437466616568
注意 转载须保留原文链接,译文链接,作者译者等信息。  
nginx安全下载模块可以给服务器文件链接添加时间戳和校验码,从而保护服务器文件不被任意下载盗用。nginx的ngx_http_secure_link_module模块和lighttpd的sec_download模块功能类似,配置更简单。

首先检查nginx是否已安装模块
#nginx -V
输出nginx所有已安装模块,检查是否有ngx_http_secure_link_module

配置nginx
#vi /etc/nginx/conf.d/cms.conf
location /sec/ {
root /soft/xlongwei;
secure_link $arg_st,$arg_e;
secure_link_md5 segredo$uri$arg_e; #segredo为密码样例
if ( $secure_link = "" ) {
return 402;
}
if ( $secure_link = "0" ) {
return 405;
}
}

用php生成测试安全下载链接,由于配置有discuz版的bbs.xlongwei.com,所以直接在discuz目录编辑sec.php即可测试
#vi /soft/discuz/sec.php
<?php
$secret = 'segredo'; // secrets
$path = "/".$_REQUEST["f"]; // ?f=path
$expire = time()+10; // add ? seconds to be available,这里是10妙内访问有效

$md5 = base64_encode(md5($secret . $path . $expire, true)); // Using binary hashing.
$md5 = strtr($md5, '+/', '-_'); // + and / are considered special characters in URLs, see the wikipedia page linked in references.
$md5 = str_replace('=', '', $md5); // When used in query parameters the base64 padding character is considered special.

$url = "http://cms.xlongwei.com$path?st=$md5&e=$expire"; //安全下载链接可以直接echo输出

$arr = array("url"=>$url, "expire"=>date("Y-m-d H:i:s", $expire), "md5"=>$md5);

echo json_encode($arr); //转成json格式输出也不错
?>

测试访问:http://bbs.xlongwei.com/sec.php?f=sec/test.txt
响应内容中的url:http://cms.xlongwei.com/sec/test.txt?st=FzMATYtf1urcUE5hKf01Bg&e=1437467381
如果超时后再访问会返回405

shell方式生成,http://tool.xlongwei.com/shells/sec.sh
secret=`echo segredo`
path=$1
e=`date -d "+15 seconds" +%s`
str=$secret$path$e
#echo $str
st=`echo -n $str | openssl md5 -binary | openssl base64 | tr +/ -_ | tr -d =`

url="http://cms.xlongwei.com$path?st=$st&e=$e"
echo $url

java方式生成
public class Sec {
public static String url(String path) {
String secret="segredo"; //secret
String e=String.valueOf((System.currentTimeMillis()/1000)+10); //10 seconds
String md5 = Base64.encodeBase64URLSafeString(DigestUtils.md5(secret+path+e));
return "http://cms.xlongwei.com"+path+"?st="+md5+"&e="+e;
}
}