配置Apache2的防盗链功能可以通过修改Apache的配置文件来实现。防盗链的目的是防止其他网站直接链接到你的服务器上的资源(如图片、视频等),从而节省带宽并保护资源。以下是配置防盗链的步骤:
mod_rewrite
模块启用mod_rewrite
模块:
确保mod_rewrite
模块已经启用。你可以通过以下命令启用它:
sudo a2enmod rewrite
编辑Apache配置文件:
编辑你的网站配置文件,通常位于/etc/apache2/sites-available/your-site.conf
。
添加防盗链规则:
在<Directory>
或<Location>
块中添加以下内容:
<Directory "/var/www/html">
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|jpeg|png|gif|ico|svg)$ - [F,L]
</Directory>
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查HTTP_REFERER是否不是你的域名。RewriteCond %{HTTP_REFERER} !^$
:确保HTTP_REFERER不是空的。RewriteRule \.(jpg|jpeg|png|gif|ico|svg)$ - [F,L]
:如果条件匹配,返回403 Forbidden状态码,并停止进一步处理。重启Apache: 保存配置文件后,重启Apache以应用更改:
sudo systemctl restart apache2
mod_security
模块如果你已经安装了mod_security
模块,可以使用它来配置防盗链。
启用mod_security
模块:
确保mod_security
模块已经启用。你可以通过以下命令启用它:
sudo a2enmod security2
编辑Apache配置文件:
编辑你的网站配置文件,通常位于/etc/apache2/sites-available/your-site.conf
。
添加防盗链规则:
在<Directory>
或<Location>
块中添加以下内容:
<Directory "/var/www/html">
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif|ico|svg)$" \
"id:1234567,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Access denied to direct linking'"
</Directory>
解释:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif|ico|svg)$"
:匹配请求的文件名是否以指定的图片扩展名结尾。id:1234567
:规则的唯一标识符。phase:2
:规则在请求处理的第二阶段执行。deny
:拒绝访问。status:403
:返回403 Forbidden状态码。log
:记录日志。msg:'Access denied to direct linking'
:日志消息。重启Apache: 保存配置文件后,重启Apache以应用更改:
sudo systemctl restart apache2
通过以上步骤,你可以有效地配置Apache2的防盗链功能,保护你的资源不被非法链接。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: ubuntu如何修改ip地址和网关