centos

centos apache2防盗链方法

小樊
41
2025-05-27 02:59:01
栏目: 智能运维

在 CentOS 系统上,Apache 服务器可以通过配置 .htaccess 文件来实现防盗链功能。以下是一些常用的防盗链方法:

  1. 使用 mod_rewrite 模块:

    在需要防盗链的目录下创建或编辑 .htaccess 文件,添加以下内容:

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

    yourdomain.com 替换为你自己的域名。这段代码会检查访问者的 HTTP_REFERER,如果不是来自你指定的域名,将拒绝访问图片文件。

  2. 使用 mod_authz_coremod_authz_host 模块:

    在 Apache 配置文件(如 /etc/httpd/conf/httpd.conf/etc/httpd/conf.d/yourdomain.conf)中添加以下内容:

    <Directory "/path/to/your/protected/directory">
        AuthType Basic
        AuthName "Restricted Content"
        AuthUserFile /etc/httpd/.htpasswd
        Require host yourdomain.com
    </Directory>
    

    /path/to/your/protected/directory 替换为你需要保护的目录路径,将 yourdomain.com 替换为你自己的域名。这段代码会要求访问者使用指定的用户名和密码才能访问该目录下的内容。

  3. 使用第三方模块 mod_security:

    安装 mod_security 模块:

    sudo yum install mod_security
    

    启用 mod_security 模块:

    sudo systemctl enable mod_security
    sudo systemctl start mod_security
    

    在 Apache 配置文件(如 /etc/httpd/conf/httpd.conf/etc/httpd/conf.d/yourdomain.conf)中添加以下内容:

    <Location "/path/to/your/protected/directory">
        SecRule REQUEST_URI "@endsWith .(jpg|jpeg|png|gif)$" \
            "id:1234567,\
            phase:2,\
            deny,\
            status:403,\
            log,\
            msg:'Access to images is restricted'"
    </Location>
    

    /path/to/your/protected/directory 替换为你需要保护的目录路径。这段代码会拒绝访问指定目录下的图片文件。

注意:在进行上述操作之前,请确保已经备份了相关配置文件,以便在出现问题时可以恢复。

0
看了该问题的人还看了