在CentOS上配置Apache服务器以防止防盗链,可以通过以下步骤实现:
如果你还没有安装Apache,可以使用以下命令进行安装:
sudo yum install httpd sudo systemctl start httpd sudo systemctl enable httpd 防盗链通常是通过检查HTTP请求头中的Referer字段来实现的。你可以在Apache配置文件中添加一个<Location>或<Directory>块来实现防盗链。
mod_rewrite模块确保mod_rewrite模块已启用:
sudo yum install mod_rewrite sudo systemctl restart httpd 编辑Apache配置文件(通常是/etc/httpd/conf/httpd.conf或/etc/httpd/conf.d/yourdomain.conf),添加以下内容:
<Directory "/var/www/html"> RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L] </Directory> 这里的yourdomain.com是你的域名,/var/www/html是你的网站根目录。
mod_authz_core和mod_authz_host模块确保mod_authz_core和mod_authz_host模块已启用:
sudo yum install mod_authz_core mod_authz_host sudo systemctl restart httpd 编辑Apache配置文件,添加以下内容:
<Directory "/var/www/html"> AuthType None Require all granted SetEnvIf Referer "^$" dontlog SetEnvIf Referer ".*yourdomain\.com" allowed_referer Order allow,deny Allow from env=allowed_referer Satisfy Any </Directory> 这里的yourdomain.com是你的域名,/var/www/html是你的网站根目录。
保存配置文件后,重启Apache服务以应用更改:
sudo systemctl restart httpd 然后尝试从不同的域名访问你的图片资源,确保防盗链配置生效。
通过以上步骤,你应该能够在CentOS上成功配置Apache服务器以防止防盗链。