在CentOS上配置Apache2以实现防盗链,可以通过以下步骤来完成:
首先,确保你的CentOS系统上已经安装了Apache2。如果没有安装,可以使用以下命令进行安装:
sudo yum install httpd
安装完成后,启动Apache2服务并设置开机自启:
sudo systemctl start httpd
sudo systemctl enable httpd
防盗链通常是通过检查HTTP请求头中的Referer
字段来实现的。以下是一个基本的防盗链配置示例:
在/etc/httpd/conf.d/
目录下创建一个新的配置文件,例如hotlinking.conf
:
sudo vi /etc/httpd/conf.d/hotlinking.conf
在hotlinking.conf
文件中添加以下内容:
<Directory "/var/www/html">
# 允许的域名列表
SetEnvIf Referer "^http(s)?://(www\.)?example\.com$" allow_referer
SetEnvIf Referer "^$" deny_referer
# 拒绝所有不符合条件的请求
Order Allow,Deny
Allow from env=allow_referer
Deny from all
# 可选:自定义403错误页面
ErrorDocument 403 /403.html
</Directory>
在这个配置中:
SetEnvIf Referer "^http(s)?://(www\.)?example\.com$" allow_referer
:允许来自example.com
及其子域名的请求。SetEnvIf Referer "^$" deny_referer
:拒绝没有Referer
头的请求。Order Allow,Deny
、Allow from env=allow_referer
、Deny from all
:设置访问控制规则。如果你希望自定义403错误页面,可以在/var/www/html/
目录下创建一个403.html
文件:
sudo vi /var/www/html/403.html
在文件中添加你希望显示的内容,例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Access Denied</title>
</head>
<body>
<h1>Access Denied</h1>
<p>You do not have permission to access this resource.</p>
</body>
</html>
保存并关闭所有文件后,重启Apache2服务以使配置生效:
sudo systemctl restart httpd
你可以通过以下方式测试防盗链配置是否生效:
通过以上步骤,你可以在CentOS上配置Apache2以实现基本的防盗链功能。根据实际需求,你可以进一步调整和优化防盗链规则。