在Apache中配置防盗劫持(也称为防盗链或Hotlink Protection)可以通过多种方法实现,以下是一些常见的方法:

mod_rewrite模块启用mod_rewrite模块:确保Apache的mod_rewrite模块已启用。可以通过以下命令启用:
sudo a2enmod rewritesudo systemctl restart apache2配置防盗链:在网站的.htaccess文件或Apache配置文件中添加以下规则:
RewriteEngine OnRewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com [NC]RewriteCond %{HTTP_REFERER} !^$RewriteRule .(jpg|jpeg|png|gif)$ - [F,L]解释:
RewriteEngine On:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com [NC]:检查请求的Referer是否不是你的域名(忽略大小写)。RewriteCond %{HTTP_REFERER} !^$:确保Referer不是空的。RewriteRule .(jpg|jpeg|png|gif)$ - [F,L]:如果条件匹配,则返回403 Forbidden状态码,并停止进一步处理。mod_headers模块启用mod_headers模块:确保Apache的mod_headers模块已启用。可以通过以下命令启用:
sudo a2enmod headerssudo systemctl restart apache2配置防盗链:在网站的.htaccess文件或Apache配置文件中添加以下规则:
<IfModule mod_headers.c>RewriteEngine OnRewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com [NC]RewriteCond %{HTTP_REFERER} !^$Header set X-Frame-Options "SAMEORIGIN"Header set Content-Security-Policy "frame-ancestors 'self'"</IfModule>解释:
Header set X-Frame-Options "SAMEORIGIN":防止页面被其他域名的iframe嵌入。Header set Content-Security-Policy "frame-ancestors 'self'":设置内容安全策略,防止页面被其他域名的iframe嵌入。如果你需要更复杂的防盗链功能,可以考虑使用第三方模块,如mod_security。
安装mod_security:
sudo apt-get install libapache2-mod-security2sudo systemctl restart apache2配置防盗链:在/etc/modsecurity/modsecurity.conf或/etc/apache2/conf-available/security2.conf文件中添加规则:
SecRule REQUEST_FILENAME ".(jpg|jpeg|png|gif)$" "id:1234567,phase:2,deny,status:403,log,msg:'Hotlinking detected'"解释:
SecRule REQUEST_FILENAME ".(jpg|jpeg|png|gif)$":匹配请求的文件类型。id:1234567:规则的唯一标识符。phase:2:规则执行的阶段。deny:拒绝请求。status:403:返回403 Forbidden状态码。log:记录日志。msg:'Hotlinking detected':日志消息。.htaccess文件。通过以上方法,你可以在Apache中有效地配置防盗劫持,保护你的网站资源不被非法使用。
DeepSeek多模态怎么样及保姆级配置教程(codex、claude)实用指南
WSL2+Docker+Ollama本地部署大模型思路和实践指南(Qwen1.8b)实用指南
DeepSeek Harness热门插件盘点:10个实用插件,覆盖多Agent、上下文和多模态实用指南
grep文本搜索与正则表达式完整代码示例实用指南
AI漫剧伪装直男1‑24集无雾版夸克网盘资源免费分享
AI漫剧玉僧入尘1-68集无雾无删版夸克网盘资源免费分享