温馨提示×

Ubuntu中Apache2的防盗链怎么设置

小樊
42
2025-09-07 06:40:21
栏目: 智能运维

在Ubuntu中,要为Apache2设置防盗链,你可以使用mod_rewrite模块。请按照以下步骤操作:

  1. 确保mod_rewrite已启用。在终端中运行以下命令:
sudo a2enmod rewrite
  1. 重启Apache2服务以应用更改:
sudo systemctl restart apache2
  1. 打开你的网站配置文件。通常位于/etc/apache2/sites-available/目录下,例如000-default.conf。使用文本编辑器打开,如nano:
sudo nano /etc/apache2/sites-available/000-default.conf
  1. <VirtualHost>部分内,找到DocumentRoot指令。它指向你的网站文件所在的目录。例如:
DocumentRoot /var/www/html
  1. DocumentRoot下方添加以下代码:
<Directory "/var/www/html">
    RewriteEngine On
    RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
    RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
</Directory>

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

  1. 保存并关闭文件。

  2. 重新启动Apache2服务以应用更改:

sudo systemctl restart apache2

现在,你的Apache2服务器已经设置了防盗链。未经授权的用户将无法访问你网站上指定的文件类型。

0