🔒 防盗链配置全攻略 | A Complete Guide to Hotlink Protection

防盗链封面图

🌟 前言 | Introduction

在网站运营中,我们经常会遇到资源被其他站点直接链接使用的情况,这不仅消耗我们的服务器带宽,还可能带来额外的流量费用。今天,我们来详细探讨如何配置防盗链保护你的宝贵资源!✨

In website management, we often encounter situations where resources are directly linked by other sites. This not only consumes our server bandwidth but may also incur additional traffic costs. Today, let's explore in detail how to configure hotlink protection for your valuable resources! ✨


防盗链(Hotlink Protection) 是一种防止其他网站直接链接到你服务器上资源(如图片、视频、文件等)的技术。当检测到请求来源不是你的授权站点时,服务器会拒绝访问或返回替代内容。

Hotlink Protection is a technique that prevents other websites from directly linking to resources (such as images, videos, files, etc.) on your server. When it detects that the request source is not from your authorized sites, the server will deny access or return alternative content.

🎯 主要目的 | Main Purposes

  • 节省带宽 🚀 - 防止资源被盗用
  • 保护版权 ©️ - 确保内容所有权
  • 提升安全 🔐 - 减少不必要的请求

🛠️ 配置指南 | Configuration Guide

环境准备 | Environment Preparation

确保你拥有服务器配置权限,并了解基本的服务器配置知识。📚

Ensure you have server configuration privileges and understand basic server configuration knowledge. 📚


# 📁 在 server 或 location 块中添加 | Add in server or location block
location ~* \.(jpg|jpeg|png|gif|ico|css|js|pdf|mp4|webm)$ {
    # ✅ 允许的域名列表 | Allowed domain list
    valid_referers none blocked server_names
               *.yourdomain.com
               yourdomain.com
               localhost
               ~\.google\. ~\.bing\. ~\.yahoo\.
               ~\.baidu\. ~\.sogou\. ~\.so\.;
    
    # 🚫 如果来源不在列表中 | If referer not in list
    if ($invalid_referer) {
        # 可选项:返回403错误 | Option: Return 403 error
        return 403;
        
        # 或返回默认图片 | Or return default image
        # rewrite ^ /images/blocked.png break;
    }
    
    # 设置过期时间(可选)| Set expiration (optional)
    expires 30d;
    add_header Cache-Control "public, immutable";
}

🔍 配置说明 | Configuration Explanation

  • valid_referers:定义合法的引用来源
  • none:允许直接访问(无Referer)
  • blocked:允许Referer被防火墙修改的请求
  • 支持正则表达式匹配搜索引擎

# 📁 在 .htaccess 或配置文件中添加 | Add in .htaccess or config file
<IfModule mod_rewrite.c>
    RewriteEngine On
    
    # 🛡️ 保护特定文件类型 | Protect specific file types
    RewriteCond %{HTTP_REFERER} !^$
    RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/.*$ [NC]
    RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourotherdomain\.com/.*$ [NC]
    
    # 🔍 允许搜索引擎 | Allow search engines
    RewriteCond %{HTTP_REFERER} !google\. [NC]
    RewriteCond %{HTTP_REFERER} !bing\. [NC]
    RewriteCond %{HTTP_REFERER} !yahoo\. [NC]
    RewriteCond %{HTTP_REFERER} !baidu\. [NC]
    
    # 🚫 不匹配时的处理 | Handling for non-matching
    RewriteRule \.(jpg|jpeg|png|gif|mp4|pdf)$ - [NC,F,L]
    
    # 或显示替代图片 | Or show alternative image
    # RewriteRule \.(jpg|jpeg|png|gif)$ /images/blocked.png [NC,L,R]
</IfModule>

🧪 测试与验证 | Testing and Verification

测试方法 | Testing Methods

  1. 直接访问测试 🔗

    curl -I https://yourdomain.com/image.jpg
    
  2. 模拟外部引用 🌐

    curl -I -H "Referer: https://unauthorized-site.com" https://yourdomain.com/image.jpg
    
  3. 使用浏览器开发者工具 🔧

    • 在不同站点中测试图片加载
    • 检查网络请求状态码

📊 预期结果 | Expected Results

场景 状态码 说明
直接访问 200 ✅ 正常访问
授权站点引用 200 ✅ 正常加载
未授权站点引用 403/404 ❌ 访问被拒绝

🎨 高级技巧 | Advanced Techniques

1. 动态替换内容 | Dynamic Content Replacement

location ~* \.(jpg|jpeg|png|gif)$ {
    valid_referers blocked server_names *.yourdomain.com;
    
    if ($invalid_referer) {
        # 🔄 重写到水印图片 | Rewrite to watermarked image
        rewrite ^ /watermark.php?url=$request_uri break;
    }
}

2. CDN 配合配置 | CDN Configuration

如果你使用CDN服务,还需要在CDN控制台进行相应设置:

If using CDN services, additional configuration is needed in the CDN console:

  • 设置Referer白名单 📝
  • 开启防盗链功能 🛡️
  • 配置自定义错误页面 ⚙️

3. 日志监控 | Log Monitoring

# 📈 记录盗链请求 | Log hotlink requests
log_format hotlink '$remote_addr - $invalid_referer - $http_referer - $request';
access_log /var/log/nginx/hotlink.log hotlink;

💡 最佳实践 | Best Practices

  1. 逐步实施 🐢 - 先监控再拦截
  2. 保留搜索引擎访问 🔍 - 确保SEO不受影响
  3. 定期更新白名单 📅 - 添加合作伙伴域名
  4. 监控带宽变化 📊 - 评估防护效果
  5. 设置友好的错误页面 ❤️ - 提升用户体验

⚠️ 注意事项 | Important Notes

  • 测试充分 🧪 - 上线前全面测试
  • 备份配置 💾 - 修改前备份原文件
  • 考虑API请求 🔄 - 确保API接口不受影响
  • 移动端兼容 📱 - 测试移动设备访问

🎯 总结 | Conclusion

防盗链配置是网站资源保护的重要环节,合理的配置可以有效节省带宽成本、保护知识产权。根据你的实际需求选择合适的配置方案,并定期维护更新。

记住:安全与用户体验需要平衡 ⚖️

Hotlink protection is a crucial aspect of website resource security. Proper configuration can effectively save bandwidth costs and protect intellectual property. Choose the appropriate configuration based on your actual needs and maintain it regularly.

Remember: Balance security with user experience ⚖️


📚 扩展阅读 | Further Reading


🤝 交流与反馈 | Communication & Feedback

遇到问题或有更好建议?欢迎在评论区留言讨论! 💬

Encountering issues or have better suggestions? Feel free to leave a comment below! 💬