在CentOS上配置Apache防盗链,可以通过修改Apache的配置文件来实现。防盗链的目的是防止其他网站直接链接到你的服务器上的资源(如图片、视频等),从而节省带宽并保护你的资源。以下是详细的步骤:
1. 安装Apache
如果你还没有安装Apache,可以使用以下命令进行安装:
sudo yum install httpd
2. 启动Apache服务
安装完成后,启动Apache服务并设置开机自启动:
sudo systemctl start httpd sudo systemctl enable httpd
3. 配置防盗链
编辑Apache的配置文件/etc/httpd/conf/httpd.conf
或创建一个新的配置文件(例如/etc/httpd/conf.d/anti-hotlinking.conf
)。
方法一:直接在httpd.conf
中配置
打开/etc/httpd/conf/httpd.conf
文件:
sudo vi /etc/httpd/conf/httpd.conf
在文件的末尾添加以下内容:
Options -Indexes FollowSymLinks AllowOverride None Require all granted Order allow,deny Deny from all Allow from env=allowed_referrer SetEnvIf Referer "^$" allowed_referrer
这段配置的意思是:
- 对于所有图片文件(jpg, jpeg, png, gif, ico),默认拒绝所有访问。
- 只有当Referer头匹配
allowed_referrer
环境变量时,才允许访问。
方法二:创建一个新的配置文件
创建一个新的配置文件/etc/httpd/conf.d/anti-hotlinking.conf
:
sudo vi /etc/httpd/conf.d/anti-hotlinking.conf
在文件中添加以下内容:
Options -Indexes FollowSymLinks AllowOverride None Require all granted Order allow,deny Deny from all Allow from env=allowed_referrer SetEnvIf Referer "^$" allowed_referrer
4. 设置允许的Referer
在同一个配置文件中,添加允许的Referer。例如,如果你想允许来自http://example.com
的请求,可以添加以下内容:
SetEnvIf Referer "^http://example\.com$" allowed_referrer
如果你想允许多个域名,可以使用正则表达式:
SetEnvIf Referer "^https?://(www\.)?(example\.com|anotherdomain\.com)$" allowed_referrer
5. 重启Apache服务
保存配置文件并重启Apache服务以使更改生效:
sudo systemctl restart httpd
6. 测试配置
你可以通过以下方式测试防盗链配置是否生效:
- 在浏览器中访问你的网站资源。
- 使用浏览器的开发者工具查看网络请求的Referer头。
- 确保只有来自允许域名的请求能够成功加载资源。
通过以上步骤,你就可以在CentOS上成功配置Apache防盗链了。