在 CentOS 上配置 Apache2 防盗链,可以通过修改 Apache 的配置文件来实现。以下是详细的步骤:
1. 安装 Apache
首先,确保你的 CentOS 系统上已经安装了 Apache。如果没有安装,可以使用以下命令进行安装:
sudo yum install httpd
2. 启动 Apache 服务
安装完成后,启动 Apache 服务并设置开机自启动:
sudo systemctl start httpd
sudo systemctl enable httpd
3. 配置防盗链
防盗链通常是通过检查 HTTP 请求头中的 Referer 字段来实现的。你可以在 Apache 的配置文件中添加相应的规则来实现防盗链。
方法一:使用 .htaccess 文件
在需要保护的目录下创建或编辑 .htaccess 文件,添加以下内容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
解释:
RewriteEngine On:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:检查请求的Referer是否不是来自yourdomain.com或www.yourdomain.com。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]:如果条件匹配,返回 403 Forbidden 状态码,并停止进一步处理。
方法二:使用主配置文件
如果你不想使用 .htaccess 文件,可以直接在 Apache 的主配置文件中添加规则。编辑 /etc/httpd/conf/httpd.conf 文件,或者在 /etc/httpd/conf.d/ 目录下创建一个新的配置文件,例如 mydomain.conf,添加以下内容:
:80>
ServerName yourdomain.com
DocumentRoot /var/www/html
"/var/www/html/protected">
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
解释:
:定义一个虚拟主机,监听 80 端口。ServerName yourdomain.com:设置服务器名称。DocumentRoot /var/www/html:设置网站根目录。:指定需要保护的目录。- 其余部分与
.htaccess文件中的规则相同。
4. 重启 Apache 服务
修改配置文件后,重启 Apache 服务以使更改生效:
sudo systemctl restart httpd
5. 测试防盗链
现在,你可以测试防盗链是否生效。尝试从不同的域名访问受保护的资源,确保只有来自允许域名的请求才能访问。
通过以上步骤,你可以在 CentOS 上成功配置 Apache2 的防盗链功能。