温馨提示×

如何配置CentOS Apache的防盗链

小樊
47
2025-08-24 18:42:55
栏目: 智能运维

在CentOS上配置Apache服务器以防止防盗链,可以通过以下步骤实现:

1. 安装Apache

如果你还没有安装Apache,可以使用以下命令进行安装:

sudo yum install httpd 

2. 启动和启用Apache服务

sudo systemctl start httpd sudo systemctl enable httpd 

3. 配置防盗链

防盗链通常是通过检查HTTP请求头中的Referer字段来实现的。你可以在Apache配置文件中添加一个<Location><Directory>块来实现防盗链。

方法一:使用mod_rewrite模块

  1. 确保mod_rewrite模块已启用:

    sudo yum install mod_rewrite sudo systemctl restart httpd 
  2. 编辑Apache配置文件(通常是/etc/httpd/conf/httpd.conf/etc/httpd/conf.d/yourdomain.conf),添加以下内容:

    <Directory "/var/www/html"> RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC] RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L] </Directory> 

    这里的yourdomain.com是你的域名,/var/www/html是你的网站根目录。

方法二:使用mod_authz_coremod_authz_host模块

  1. 确保mod_authz_coremod_authz_host模块已启用:

    sudo yum install mod_authz_core mod_authz_host sudo systemctl restart httpd 
  2. 编辑Apache配置文件,添加以下内容:

    <Directory "/var/www/html"> AuthType None Require all granted SetEnvIf Referer "^$" dontlog SetEnvIf Referer ".*yourdomain\.com" allowed_referer Order allow,deny Allow from env=allowed_referer Satisfy Any </Directory> 

    这里的yourdomain.com是你的域名,/var/www/html是你的网站根目录。

4. 测试配置

保存配置文件后,重启Apache服务以应用更改:

sudo systemctl restart httpd 

然后尝试从不同的域名访问你的图片资源,确保防盗链配置生效。

注意事项

  • 确保你的防火墙允许HTTP(端口80)和HTTPS(端口443)流量。
  • 如果你使用的是SSL证书,确保在配置文件中正确设置了SSL相关的指令。

通过以上步骤,你应该能够在CentOS上成功配置Apache服务器以防止防盗链。

0