ubuntu

Ubuntu Apache防盗链实现方法

小樊
47
2025-03-21 03:50:19
栏目: 智能运维

在Ubuntu上使用Apache服务器实现防盗链,可以通过配置Apache的mod_rewrite模块来实现。以下是详细的步骤:

1. 安装Apache和mod_rewrite模块

首先,确保你的Ubuntu系统上已经安装了Apache服务器和mod_rewrite模块。

sudo apt update
sudo apt install apache2
sudo a2enmod rewrite

2. 配置防盗链

编辑Apache的配置文件或网站的虚拟主机配置文件。通常,这些文件位于/etc/apache2/sites-available/目录下。

方法一:全局配置

如果你希望对所有网站生效,可以编辑/etc/apache2/apache2.conf文件。

sudo nano /etc/apache2/apache2.conf

在文件的末尾添加以下内容:

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

yourdomain.com替换为你的实际域名。

方法二:针对特定网站配置

如果你只想对特定网站生效,可以编辑该网站的虚拟主机配置文件。例如,如果你的网站配置文件是/etc/apache2/sites-available/yourdomain.com.conf,则编辑该文件:

sudo nano /etc/apache2/sites-available/yourdomain.com.conf

<VirtualHost *:80>块中添加以下内容:

<VirtualHost *:80>
    ServerAdmin webmaster@yourdomain.com
    DocumentRoot /var/www/html

    <Directory "/var/www/html">
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

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

3. 重启Apache服务器

保存并关闭文件后,重启Apache服务器以使配置生效。

sudo systemctl restart apache2

4. 测试防盗链

现在,你可以测试防盗链是否生效。尝试从其他域名访问你的图片资源,应该会收到403 Forbidden错误。

注意事项

通过以上步骤,你可以在Ubuntu上使用Apache服务器实现防盗链功能。

0
看了该问题的人还看了