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.comhttps://example.com,就返回 403 禁止访问。
  • location /download/ 表示只对带有 /download/ 前缀的请求进行防盗链处理。
  • secure_link_secret 指定了加密用的密钥。
  • secure_link $arg_md5,$arg_expires 表示对 URL 中的 md5expires 参数进行加密。
  • 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; 表示将请求重写为实际的文件路径
nginx http_secure_link 防盗代码完整示例

原文地址: https://www.cveoy.top/t/topic/fJwp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录