温馨提示×

如何在CentOS上配置Apache2防盗版

小樊
43
2025-09-03 19:12:38
栏目: 智能运维

在CentOS上配置Apache2防盗版(防盗链)主要有以下两种方法:

  • 通过修改配置文件
    1. 安装Apache2:sudo yum install httpd
    2. 启动并启用服务:sudo systemctl start httpdsudo systemctl enable httpd
    3. 编辑配置文件,可在/etc/httpd/conf/httpd.conf/etc/httpd/conf.d/下新建如anti - hotlinking.conf文件,添加规则:
      • 基础规则示例:
        <Directory "/var/www/html">
            RewriteEngine On
            RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain\.com [NC]
            RewriteCond %{HTTP_REFERER} !^$
            RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
        </Directory>
        
      • 规则解释:启用重写引擎,检查Referer头,若不是来自指定域名且不为空,则拒绝访问图片等资源。
    4. 重启服务:sudo systemctl restart httpd
  • 使用.htaccess文件
    1. 进入网站根目录(通常/var/www/html),创建或编辑.htaccess文件。
    2. 添加内容:
      RewriteEngine On
      RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain\.com [NC]
      RewriteCond %{HTTP_REFERER} !^$
      RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
      
    3. 确保Apache配置允许使用.htaccess文件(若为虚拟主机,在相应配置中设置AllowOverride All)。
    4. 重启Apache服务:sudo systemctl restart httpd

以上配置中,yourdomain.com需替换为实际域名,可根据需求调整允许的域名和文件类型。

0