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;表示将请求重写为实际的文件路径
原文地址: https://www.cveoy.top/t/topic/fJwp 著作权归作者所有。请勿转载和采集!