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