Nginx 反向代理技术绕过防盗链方案
用于从微信图床(mmbiz.qpic.cn)加载图片时伪造请求头,以绕过 Referer 检查
定义一个路径 /mmbiz,当用户访问这个路径时,触发以下代理规则
nginx
location /mmbiz {
# 核心逻辑:伪造请求头
proxy_set_header referer "https://mp.weixin.qq.com";
# 设置 Origin 头,进一步伪装成微信来源,某些服务器会同时检查 Origin 和 Referer
proxy_set_header origin "https://mp.weixin.qq.com";
# 模拟一个常见的浏览器 UA,避免被识别为爬虫或脚本
proxy_set_header user-agent "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36";
# 实现反向代理:用户访问 /mmbiz/xxx.jpg,实际上是访问 http://mmbiz.qpic.cn/xxx.jpg,但由你的服务器代为请求。意 proxy_pass 的域名最后带了 /,表示保留原始 URI 的后缀部分
proxy_pass http://mmbiz.qpic.cn/;
}
带/ 和 不带/
| 配置方式 | 请求路径 | 转发结果 |
|---|---|---|
proxy_pass http://host/; |
/mmbiz/xyz.jpg |
http://host/xyz.jpg |
proxy_pass http://host; |
/mmbiz/xyz.jpg |
http://host/mmbiz/xyz.jpg |
如何防盗链,防盗链在 web 服务器上的配置
对于个人博客/小网站来说,防盗链会屏蔽搜索引擎,得不偿失
Nginx:
location /images/ {
# valid_referers 是 Nginx 内置变量,该配置运行3种情况拉取资源:none blocked *.yourdomain.com
# 1. none,即无 referers(直接输入URL,或API调用);2. blocked,Referer 被浏览器或代理屏蔽的情况(Referer 为空);3. 允许的域名:*.yourdomain.com(注意:yourdomain.com 也是 *.yourdomain.com 的一种,根域等同于空子域)
valid_referers none blocked *.yourdomain.com;
if ($invalid_referer) {
return 403;
}
}
Apache:
# 启用mod_rewrite模块的重写引擎
RewriteEngine on
# 用条件语句(Condition)检查 %{HTTP_REFERER}(Apache变量,Referer头值),!^$正则,!:非;^$:空,即非空时继续执行下一语句
RewriteCond %{HTTP_REFERER} !^$
# 同上,不是你的域名,继续下一语句,[NC]即不区分大小写(No Case),如果 Referer是 https://yourdomain.com.xxxsite.com/ 也能访问,更安全的写法是!^https?://([^/]+\.)*yourdomain\.com/(精确匹配域名)
RewriteCond %{HTTP_REFERER} !yourdomain\.com [NC]
# 重写规则(Rule),定义当条件满足时执行。\.是文件扩展名,执行[F]:标志,返回Forbidden(403),拒绝访问
RewriteRule \.(jpg|png|gif)$ - [F]
Apache的逻辑没有Nginx那么直接:Referer头值非空,且不是来自你的域名,就返回403
该配置代码通常放在 .htaccess中(需AllowOverride All),或httpd.conf的
Caddy:
yourdomain.com {
# 静态文件服务(可选,如果是文件服务器)
file_server
# 定义图片路径匹配器(OR 逻辑),为真则执行下一条
@images {
path *.jpg *.jpeg *.png *.gif *.svg
}
@allowed_referer {
header Referer "" # 允许直接打开
header Referer *yourdomain.com* # 允许自己
header Referer *google.com* # 允许google
header Referer *partner2.net* # 允许合作方
}
# 定义热链匹配器:是图片 且 不允许的Referer
@hotlink {
@images
not @allowed_referer
}
# 对无效 Referer 返回 403
respond @hotlink "Hotlinking not allowed" 403 {
close
}
}