在开始配置前,需确保系统已安装Nginx且服务正常运行。若未安装,可通过以下命令完成安装:
sudo apt update && sudo apt install nginx -y
Debian系统中,Nginx的主配置文件通常位于/etc/nginx/nginx.conf,而虚拟主机配置多在/etc/nginx/sites-available/default(默认站点)。建议编辑默认站点配置文件:
sudo nano /etc/nginx/sites-available/default
在server块内(或针对特定location块,如资源目录),添加以下配置:
server {
listen 80;
server_name yourdomain.com www.yourdomain.com; # 替换为你的域名
# 防盗链配置(针对所有路径)
location / {
valid_referers none blocked server_names yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403; # 返回403 Forbidden禁止访问
# 可选:重定向到自定义禁止页面
# rewrite ^ /static/nohotlink.html;
}
root /var/www/html; # 网站根目录
index index.html;
}
# 针对特定资源类型(如图片、CSS、JS)的精细化防盗链
location ~* \.(jpg|jpeg|png|gif|ico|css|js|mp4|webp)$ {
valid_referers none blocked yourdomain.com *.yourdomain.com trusted.domain.com;
if ($invalid_referer) {
return 403;
}
}
}
配置说明:
valid_referers:定义允许的引用来源,常用参数包括:
none:允许直接访问(无Referer头,如用户手动输入URL);blocked:允许被Nginx拦截的Referer(如某些防火墙或代理服务器修改后的Referer);server_names:允许当前站点域名(yourdomain.com);*.yourdomain.com:允许当前站点的所有子域名(如sub.yourdomain.com);trusted.domain.com):允许指定外部域名引用资源。if ($invalid_referer):检查Referer是否在valid_referers列表中,若不在则触发return 403(或重定向到自定义页面)。location ~* \.(...):使用正则表达式匹配特定文件类型(如图片、视频),实现精细化防盗链。按Ctrl+X→Y→Enter保存配置文件并退出。
在重新加载Nginx前,需验证配置文件是否有语法错误:
sudo nginx -t
若输出nginx: configuration file /etc/nginx/nginx.conf test is successful,则表示配置正确。
使配置生效:
sudo systemctl reload nginx
或使用快捷命令:
sudo nginx -s reload
从允许的域名(如yourdomain.com)页面访问资源(如图片),应能正常加载(HTTP状态码200)。
http://yourdomain.com/image.jpg),此时Referer为空,若配置中包含none则允许访问,否则返回403。baddomain.com)的页面链接资源,应返回403 Forbidden错误。若某些目录(如/public/)不需要防盗链,可添加排除规则:
location /public/ {
# 不进行防盗链限制
}
将非法请求重定向到自定义提示页面(如/static/nohotlink.html),提升用户体验:
if ($invalid_referer) {
rewrite ^ /static/nohotlink.html;
}
防止盗链的同时,限制资源缓存,减少不必要的流量消耗:
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
add_header Cache-Control "no-cache, no-store, must-revalidate";
add_header Pragma "no-cache";
add_header Expires "0";
}
若需禁止某些恶意域名访问资源,可使用以下规则:
if ($http_referer ~* "baddomain\.com|evil\.com") {
return 403;
}
none参数;若无需允许,可从valid_referers中移除none。if指令会轻微增加Nginx处理开销,建议避免在location块中过度使用复杂逻辑。