在Apache中配置防盗劫持(也称为防盗链或Hotlink Protection)可以通过多种方法实现,以下是几种常见的方法:
mod_rewrite
模块启用mod_rewrite
模块:
确保你的Apache服务器已经启用了mod_rewrite
模块。你可以在httpd.conf
或apache2.conf
文件中找到以下行并取消注释:
LoadModule rewrite_module modules/mod_rewrite.so
配置防盗链:
在你的网站根目录下的.htaccess
文件中添加以下内容:
RewriteEngine On
RewriteCond %{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]
:检查HTTP Referer是否不是来自你的域名。RewriteCond %{HTTP_REFERER} !^$
:确保Referer不是空的。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
:如果Referer不符合条件,则返回403 Forbidden状态码。mod_security
模块安装mod_security
模块:
如果你还没有安装mod_security
,可以使用以下命令进行安装(以Ubuntu为例):
sudo apt-get install libapache2-mod-security2
配置防盗链规则:
在/etc/modsecurity/modsecurity.conf
或/etc/apache2/conf-available/security2.conf
文件中添加以下规则:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif)$" \
"id:123456,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Hotlinking detected',\
chain"
SecRule REQUEST_HEADERS:Referer "!@rx ^http://(www\.)?yourdomain\.com$" \
"t:none"
解释:
SecRule REQUEST_FILENAME
:匹配请求的文件名。SecRule REQUEST_HEADERS:Referer
:检查HTTP Referer头。有些第三方模块或插件可以更方便地实现防盗链功能,例如:
你可以根据需要选择合适的模块或插件进行安装和配置。
通过以上方法,你可以在Apache服务器上有效地配置防盗劫持功能,保护你的网站资源不被非法使用。