在 CentOS 系统上使用 Apache2 实现防盗链功能,可以通过配置 Apache 的 mod_rewrite 模块来实现。以下是详细的步骤:
首先,确保你已经安装了 Apache 和 mod_rewrite 模块。如果没有安装,可以使用以下命令进行安装:
sudo yum install httpd
sudo systemctl start httpd
sudo systemctl enable httpd
确保 mod_rewrite 模块已经启用:
sudo systemctl enable httpd
sudo systemctl start httpd
编辑 Apache 的配置文件,通常位于 /etc/httpd/conf/httpd.conf 或 /etc/httpd/conf.d/ 目录下的某个文件(例如 default.conf)。
sudo vi /etc/httpd/conf/httpd.conf
在文件中找到 <Directory> 部分,并添加以下内容:
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
然后,在 <VirtualHost> 部分添加防盗链规则:
<VirtualHost *:80>
ServerName yourdomain.com
DocumentRoot /var/www/html
<Directory "/var/www/html">
Options FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
</VirtualHost>
RewriteEngine On:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:检查请求的 Referer 头是否不是来自你的域名。RewriteCond %{HTTP_REFERER} !^$:确保 Referer 头不为空。RewriteRule \.(jpg|jpeg|png|gif)$ - [F]:如果条件满足,则返回 403 Forbidden 状态码。保存并关闭文件后,重启 Apache 以应用更改:
sudo systemctl restart httpd
将你的图片上传到 /var/www/html 目录下,并尝试从其他域名访问这些图片。如果配置正确,你应该会看到 403 Forbidden 错误。
通过以上步骤,你就可以在 CentOS 系统上使用 Apache2 实现防盗链功能了。