centos

如何在CentOS上配置Apache防盗链

小樊
46
2025-03-25 16:44:26
栏目: 智能运维

在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

在文件的末尾添加以下内容:

<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>

这段配置的意思是:

方法二:创建一个新的配置文件

创建一个新的配置文件/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>

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. 测试配置

你可以通过以下方式测试防盗链配置是否生效:

  1. 在浏览器中访问你的网站资源。
  2. 使用浏览器的开发者工具查看网络请求的Referer头。
  3. 确保只有来自允许域名的请求能够成功加载资源。

通过以上步骤,你就可以在CentOS上成功配置Apache防盗链了。

0
看了该问题的人还看了