温馨提示×

怎样配置Nginx防盗链

小樊
36
2025-10-19 18:17:48
栏目: 编程语言

配置Nginx防盗链主要是通过设置HTTP Referer头部信息来实现的。以下是一个基本的步骤指南,帮助你配置Nginx防盗链:

  1. 打开Nginx配置文件: 通常,Nginx的主配置文件位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/default.conf。你可以使用文本编辑器打开它,例如 vimnano

    sudo vim /etc/nginx/nginx.conf
    
  2. 添加防盗链配置: 在 server 块中添加以下配置:

    server {
        listen 80;
        server_name example.com;
    
        location / {
            # 允许的域名列表
            valid_referers none blocked server_names ~\.example\.com$;
    
            if ($invalid_referer) {
                return 403 "Forbidden";
            }
    
            # 其他配置...
            root /var/www/html;
            index index.html index.htm;
        }
    }
    

    解释:

    • valid_referers none blocked server_names ~\.example\.com$;:这行配置指定了允许的Referer值。none 表示不检查Referer,blocked 表示阻止的域名,server_names 表示允许的服务器域名,~\.example\.com$ 表示允许的子域名。
    • if ($invalid_referer) { return 403 "Forbidden"; }:如果Referer无效,则返回403 Forbidden状态码。
  3. 测试配置: 在保存并关闭配置文件后,运行以下命令测试Nginx配置是否正确:

    sudo nginx -t
    

    如果配置正确,你会看到类似以下的输出:

    nginx: configuration file /etc/nginx/nginx.conf test is successful
    
  4. 重新加载Nginx: 如果配置测试通过,重新加载Nginx以应用更改:

    sudo systemctl reload nginx
    
  5. 验证防盗链: 你可以通过在不同的浏览器或使用工具(如 curl)来验证防盗链是否生效。例如,使用 curl 命令:

    curl -I http://example.com/your-image.jpg --referer http://another-site.com
    

    如果Referer不在允许列表中,你应该会收到403 Forbidden响应。

通过以上步骤,你可以成功配置Nginx防盗链,保护你的资源不被未经授权的网站引用。

0