Nginx http_secure_link 防盗链代码完整示例 - 彻底保护您的资源
Nginx http_secure_link 防盗链代码完整示例
本文提供 Nginx http_secure_link 防盗链代码完整示例,帮助您有效防止网站资源被盗链,保护您的资源安全。
server {
listen 80;
server_name example.com;
return 301 https://$server_name$request_uri;
}
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/cert;
ssl_certificate_key /path/to/key;
root /path/to/root;
index index.html;
# 防盗链
if ($http_referer !~ "^https?://(www.)?example.com") {
return 403;
}
# http_secure_link 防盗链
location /download/ {
secure_link_secret 'mysecretkey';
secure_link $arg_md5,$arg_expires;
if ($secure_link = "") {
return 403;
}
if ($secure_link = "0") {
return 410;
}
if ($secure_link = "expired") {
return 404;
}
add_header Content-Disposition 'attachment; filename=myfile.zip';
rewrite ^/download/(.*)$ /path/to/file/$1 break;
}
}
示例说明:
- 当访问
http://example.com时,会自动重定向到https://example.com。 server_name指定了服务器的域名。- SSL 相关的配置在
listen 443 ssl下。 root指定了网站的根目录。index指定了默认的首页文件。if ($http_referer !~ "^https?://(www.)?example.com")表示如果请求的 Referer 不是http://example.com或https://example.com,就返回 403 禁止访问。location /download/表示只对带有/download/前缀的请求进行防盗链处理。secure_link_secret指定了加密用的密钥。secure_link $arg_md5,$arg_expires表示对 URL 中的md5和expires参数进行加密。if ($secure_link = "")表示如果加密失败,返回 403 禁止访问。if ($secure_link = "0")表示如果链接已经过期,返回 410 Gone。if ($secure_link = "expired")表示如果链接已经过期,返回 404 Not Found。add_header Content-Disposition 'attachment; filename=myfile.zip';表示将文件以附件形式下载。rewrite ^/download/(.*)$ /path/to/file/$1 break;表示将请求重写为实际的文件路径。
其他注意事项:
secure_link_secret密钥应设置为一个随机且安全的字符串。md5和expires参数的生成方法可以根据您的实际需求进行调整。- 您也可以根据需要添加其他防盗链策略,例如使用 IP 限制、时间限制等。
使用此代码示例可以有效地保护您的网站资源,防止被盗链。
原文地址: https://www.cveoy.top/t/topic/oo6Q 著作权归作者所有。请勿转载和采集!