在Nginx中,可以通过配置防盗链策略来防止未经授权的第三方或域名访问网站的静态资源,如图片、视频等。以下是一些常见的Nginx防盗链策略:
使用valid_referers
指令:
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
valid_referers none blocked yourdomain.com *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
}
使用if
指令结合$http_referer
变量:
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
if ($http_referer !~ ^https?://(www\.)?yourdomain\.com/) {
return 403;
}
}
使用Lua脚本:
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
content_by_lua_block {
local valid_referers = { "https?://www.yourdomain.com$", "https?://yourdomain.com$" }
local referer = ngx.var.http_referer
if not valid_referers[referer] then
ngx.exit(403)
end
}
}
使用签名方式:
location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ {
access_by_lua_block {
local secret_key = "your_secret_key"
local signature = ngx.md5(ngx.var.arg_key .. ngx.var.arg_signature)
if signature ~= ngx.var.arg_signature then
ngx.exit(403)
end
}
}
在配置防盗链策略时,可以通过Nginx的日志格式化功能记录相关信息,以便于监控和审计。例如:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
通过上述配置,可以有效地防止未经授权的访问,保护网站资源的安全。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: linux底层架构从哪里开始学