documentroot本身不直接配置防盗链,需在对应块中通过mod_rewrite或setenvifnocase+filesmatch实现;启用rewriteengine,允许空referer及自身域名,对jpg等后缀返回403,或用环境变量限制访问。

DocumentRoot 本身不直接配置防盗链,防盗链需在 DocumentRoot 所在目录的上下文中,通过 重写规则(mod_rewrite) 或 Referer 白名单控制(SetEnvIfNoCase + FilesMatch) 实现。关键是在 Apache 配置中对 DocumentRoot 对应的 <directory></directory> 块启用并设置防盗链逻辑。
在 块中启用 Rewrite 规则
这是最常用、兼容性最好的方式。确保 mod_rewrite 已启用,并在 DocumentRoot 对应的 <directory></directory> 段内添加如下配置:
- 开启重写引擎:
RewriteEngine On - 允许空 Referer(用户直接在浏览器地址栏输入图片 URL 访问):
RewriteCond %{HTTP_REFERER} !^$ - 只允许你自己的域名(含 www 和非 www):
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?yourdomain\.com/ [NC] - 对常见图片后缀返回 403 禁止访问:
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,L]
完整示例(假设 DocumentRoot 是 /var/www/html):
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^https?://(www\.)?example\.com/ [NC]
RewriteRule \.(jpg|jpeg|png|gif|webp)$ - [F,L]
用 SetEnvIfNoCase + FilesMatch 更轻量地控制
适合不想依赖 mod_rewrite 的场景,也更易读。原理是:根据 Referer 设置环境变量,再按文件类型限制访问权限。
- 定义白名单 Referer(含空值):
SetEnvIfNoCase Referer "^https?://(www\.)?example\.com/" local_ref和SetEnvIfNoCase Referer "^$" local_ref - 对图片文件只允许带白名单环境变量的请求:
<filesmatch> Require env local_ref </filesmatch>
注意:Apache 2.4+ 推荐用 Require env local_ref 替代旧版的 Order/Allow/Deny。
必须确认的前提条件
- mod_rewrite 模块已加载(检查
httpd.conf中LoadModule rewrite_module modules/mod_rewrite.so未被注释) -
AllowOverride None时,规则只能写在主配置或虚拟主机中;若设为All或FileInfo,才允许 .htaccess 覆盖 - DocumentRoot 路径需与
<directory></directory>中路径完全一致(包括末尾斜杠与否),否则规则不生效 - HTTPS 域名需显式包含
https://,建议用https?://同时匹配 HTTP/HTTPS
验证是否生效
部署后可用 curl 快速测试:
- 模拟合法来源:
curl -e "https://example.com/test.html" https://example.com/images/photo.jpg -I→ 应返回200 OK - 模拟盗链来源:
curl -e "https://bad-site.com" https://example.com/images/photo.jpg -I→ 应返回403 Forbidden - 空 Referer(直接访问):
curl https://example.com/images/photo.jpg -I→ 应返回200 OK(前提是规则中保留了!^$条件)










