centos

centos中apache2如何实现防盗链功能

小樊
45
2025-05-02 21:39:23
栏目: 智能运维

在 CentOS 系统中,Apache2 服务器可以通过配置 .htaccess 文件或直接修改 Apache 配置文件来实现防盗链功能。以下是两种方法的详细步骤:

方法一:使用 .htaccess 文件

  1. 创建或编辑 .htaccess 文件: 在你的网站根目录下创建一个 .htaccess 文件(如果已经存在则直接编辑),并添加以下内容:

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

    解释:

    • RewriteEngine On:启用重写引擎。
    • RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:检查请求的来源是否不是你的域名(忽略大小写)。
    • RewriteCond %{HTTP_REFERER} !^$:确保请求的来源不是空。
    • RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]:如果条件匹配,则返回 403 Forbidden 状态码,并停止进一步处理。
  2. 保存并关闭 .htaccess 文件

方法二:修改 Apache 配置文件

  1. 编辑 Apache 配置文件: 打开 Apache 的主配置文件,通常位于 /etc/httpd/conf/httpd.conf/etc/apache2/apache2.conf,具体路径取决于你的 CentOS 版本。

    sudo vi /etc/httpd/conf/httpd.conf
    
  2. 添加防盗链配置: 在配置文件中找到 <Directory><Location> 块,添加以下内容:

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

    解释:

    • RewriteEngine On:启用重写引擎。
    • RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:检查请求的来源是否不是你的域名(忽略大小写)。
    • RewriteCond %{HTTP_REFERER} !^$:确保请求的来源不是空。
    • RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]:如果条件匹配,则返回 403 Forbidden 状态码,并停止进一步处理。
  3. 保存并关闭配置文件

  4. 重启 Apache 服务: 使配置生效,需要重启 Apache 服务:

    sudo systemctl restart httpd
    

    或者

    sudo systemctl restart apache2
    

注意事项

通过以上方法,你可以在 CentOS 系统中的 Apache2 服务器上实现防盗链功能。

0
看了该问题的人还看了