使用Nginx实现防盗链(Hotlink Protection)可以防止其他网站直接链接并显示你的资源文件,如图片、视频等。以下是实现防盗链的步骤:
编辑Nginx配置文件,通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/yourdomain.com。
valid_referers 指令server {
listen 80;
server_name yourdomain.com;
location /protected/ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
root /path/to/your/protected/files;
}
location / {
root /path/to/your/public/files;
}
}
在这个配置中:
valid_referers 指令用于指定允许的引用来源。
none 表示不允许任何引用。blocked 表示允许被Nginx阻止的引用(通常用于防止恶意请求)。yourdomain.com 和 *.yourdomain.com 表示允许你的域名及其子域名。if ($invalid_referer) 指令用于检查引用是否有效,如果无效则返回403 Forbidden状态码。ngx_http_referer_module 模块server {
listen 80;
server_name yourdomain.com;
location /protected/ {
if ($http_referer !~* "yourdomain.com|*.yourdomain.com") {
return 403;
}
root /path/to/your/protected/files;
}
location / {
root /path/to/your/public/files;
}
}
在这个配置中:
if ($http_referer !~* "yourdomain.com|*.yourdomain.com") 指令用于检查引用是否匹配指定的域名或子域名,如果不匹配则返回403 Forbidden状态码。在修改Nginx配置文件后,运行以下命令测试配置是否正确:
sudo nginx -t
如果没有错误,重新加载Nginx以应用更改:
sudo systemctl reload nginx
尝试从其他网站直接链接到你的受保护资源,应该会收到403 Forbidden响应。
valid_referers 或 ngx_http_referer_module 模块。通过以上步骤,你可以有效地使用Nginx实现防盗链功能,保护你的资源文件不被滥用。