ubuntu

Apache2在Ubuntu上如何配置防盗链

小樊
36
2025-07-06 02:17:14
栏目: 智能运维

在Ubuntu上配置Apache2防盗链,可以通过修改Apache的配置文件来实现。防盗链的主要目的是防止其他网站直接链接到你的服务器上的资源(如图片、视频等),从而节省带宽并保护你的资源。以下是配置防盗链的步骤:

方法一:使用mod_rewrite模块

  1. 启用mod_rewrite模块: 打开终端并运行以下命令来启用mod_rewrite模块:

    sudo a2enmod rewrite
    
  2. 重启Apache服务

    sudo systemctl restart apache2
    
  3. 配置防盗链: 编辑你的网站配置文件。通常,这些文件位于/etc/apache2/sites-available/目录下。你可以使用以下命令打开配置文件:

    sudo nano /etc/apache2/sites-available/your-site.conf
    

    <VirtualHost>块内添加以下内容:

    <Directory "/var/www/html">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    
    <Location "/path/to/your/resources">
        RewriteEngine On
        RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
        RewriteRule \.(jpg|jpeg|png|gif|mp4|avi)$ - [F,L]
    </Location>
    

    解释:

    • RewriteEngine On:启用重写引擎。
    • RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:检查HTTP_REFERER头,如果不是来自你的域名,则拒绝访问。
    • RewriteRule \.(jpg|jpeg|png|gif|mp4|avi)$ - [F,L]:匹配特定文件类型并返回403 Forbidden状态码。
  4. 保存并退出: 按Ctrl+X,然后按Y确认保存,最后按Enter退出。

  5. 重启Apache服务

    sudo systemctl restart apache2
    

方法二:使用mod_security模块

如果你更喜欢使用mod_security模块来实现防盗链,可以按照以下步骤操作:

  1. 安装mod_security

    sudo apt-get install libapache2-mod-security2
    
  2. 启用mod_security

    sudo a2enmod security2
    
  3. 重启Apache服务

    sudo systemctl restart apache2
    
  4. 配置防盗链规则: 编辑mod_security的配置文件:

    sudo nano /etc/modsecurity/modsecurity.conf
    

    在文件末尾添加以下规则:

    SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif|mp4|avi)$" \
        "id:1234567,\
        phase:2,\
        deny,\
        status:403,\
        log,\
        msg:'Access to resources is denied'"
    
  5. 保存并退出: 按Ctrl+X,然后按Y确认保存,最后按Enter退出。

  6. 重启Apache服务

    sudo systemctl restart apache2
    

通过以上两种方法,你可以在Ubuntu上配置Apache2防盗链,保护你的资源不被其他网站直接链接。选择适合你的方法进行配置即可。

0
看了该问题的人还看了