使用nginx http_secure_link 编写一个文件防盗代码
nginx http_secure_link 是一种用于保护静态文件的链接签名机制。它会将链接中的参数与文件路径进行加密,以防止未经授权的用户访问文件。
以下是一个使用 nginx http_secure_link 编写的文件防盗代码:
- 在 nginx.conf 文件中添加以下配置:
location /secure/ {
# 设置静态文件路径
alias /var/www/secure/;
# 禁止直接访问文件,只能通过签名链接访问
deny all;
# 获取签名链接
secure_link $arg_md5,$arg_expires;
secure_link_md5 "secret$uri$remote_addr$arg_expires";
# 根据签名链接验证文件合法性
if ($secure_link = "") {
return 403;
}
# 设置文件过期时间
if ($secure_link_expires < $date_gmt) {
return 403;
}
# 允许访问文件
if ($secure_link = "0") {
break;
}
}
- 在需要保护的文件链接中添加签名参数:
http://example.com/secure/file.png?md5=xxxxxx&expires=xxxxxx
其中,md5 参数是由服务器端生成的签名字符串,expires 参数是指定链接过期时间的时间戳。
- 在服务器端生成签名字符串的代码:
$uri = "/secure/file.png";
$secret = "secret";
$remote_addr = $_SERVER["REMOTE_ADDR"];
$expires = time() + 3600; // 设置链接有效期为 1 小时
$md5 = md5("$secret$uri$remote_addr$expires");
$link = "http://example.com$uri?md5=$md5&expires=$expires";
以上代码会生成一个有效期为 1 小时的链接,只有带有正确签名参数的链接才能访问文件。如果链接过期或签名不正确,则会返回 403 禁止访问
原文地址: https://www.cveoy.top/t/topic/fJvQ 著作权归作者所有。请勿转载和采集!