Debian 下使用 Nginx 实现防盗链
一 基本原理与准备
二 快速配置示例
server {
listen 80;
server_name yourdomain.com;
location /protected/ {
# 允许空 Referer、被防火墙屏蔽的 Referer、本站域名与子域
valid_referers none blocked server_names yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
# 其他配置(如 root、proxy_pass 等)
}
}
server {
listen 443 ssl;
server_name yourdomain.com www.yourdomain.com;
ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;
include /etc/letsencrypt/options-ssl-nginx.conf;
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
root /var/www/html;
index index.html;
# 仅对常见图片类型生效
location ~* \.(jpg|jpeg|png|gif|ico)$ {
valid_referers none blocked yourdomain.com www.yourdomain.com;
if ($invalid_referer) {
return 403;
# 也可返回警告图片:rewrite ^ /anti-hotlinking.jpg last;
}
}
}
三 生效与验证
sudo nginx -t
sudo systemctl reload nginx
curl -I https://yourdomain.com/test.jpg --header "Referer: http://evil.com"
四 进阶与注意事项