一、Nginx 带签名 URL 防盗链完整示例配置
http {
# 设置时区环境变量(方便比较时间戳)
env TZ;
server {
listen 80;
server_name secure.yourdomain.cn;
location /protected_images/ {
# 读取 URL 参数 md5 和 expires
secure_link $arg_md5,$arg_expires;
# 计算签名,这里的 secret_key 请换成你自己的密钥
secure_link_md5 "$secure_link_expires$uri secret_key";
# 签名为空,拒绝访问
if ($secure_link = "") {
return 403;
}
# 签名错误,拒绝访问
if ($secure_link = "0") {
return 403;
}
# 签名过期,拒绝访问
if ($secure_link_expires < $date_gmt) {
return 403;
}
# 符合条件,提供访问
root /usr/share/nginx/html;
}
# 普通的未保护资源
location / {
root /usr/share/nginx/html;
index index.html;
}
}
}备注
secret_key是防盗链的密钥,必须保密。建议长度较长且复杂。$date_gmt是当前 GMT 时间戳,格式为 Unix 时间戳(秒)。
二、Python 示例:生成带签名的访问 URL
import hashlib
import time
import urllib.parse
def generate_secure_url(base_url, uri, secret_key, expires_in_seconds=300):
"""
生成带签名的防盗链URL
参数:
base_url (str): 域名和协议,例如 "http://secure.yourdomain.cn"
uri (str): 资源路径,如 "/protected_images/pic1.jpg"
secret_key (str): Nginx 配置中的 secret_key
expires_in_seconds (int): 链接有效期,秒数,默认 300 秒(5分钟)
返回:
str: 完整的带签名的访问 URL
"""
expires = str(int(time.time()) + expires_in_seconds) # 过期时间戳
sign_str = expires + uri + secret_key
md5_hash = hashlib.md5(sign_str.encode('utf-8')).hexdigest()
# 构建带参数的 URL
query_params = {
'md5': md5_hash,
'expires': expires
}
return f"{base_url}{uri}?{urllib.parse.urlencode(query_params)}"
# 示例调用
if __name__ == "__main__":
base_url = "http://secure.yourdomain.cn"
uri = "/protected_images/pic1.jpg"
secret = "your_very_secret_key"
url = generate_secure_url(base_url, uri, secret)
print("生成的带签名 URL:", url)三、使用流程说明
- 配置好 Nginx 并重启
确保 Nginx 编译时包含ngx_http_secure_link_module,配置文件正确无误,执行nginx -t测试。 - 调用后端生成签名 URL
用户访问资源时,先调用后端接口获得带签名的访问链接。 - 前端使用签名 URL 资源访问
生成的 URL 过期后无法访问,防止时间之外的盗用。
四、总结建议
- 密钥要保密,不要泄露给外部,否则签名机制会失效。
- 有效期设置合理,时间太短用户体验差,太长安全性降低。
- 结合 HTTPS,防止 URL 参数被中间人截获修改。
- 如果需要更复杂的需求,例如不同权限、IP限制等,可在生成签名前端或后端加逻辑,在签名内容中加入更多字段。
作者:admin 创建时间:2025-10-20 16:34
最后编辑:admin 更新时间:2025-10-20 16:36
最后编辑:admin 更新时间:2025-10-20 16:36