在Ubuntu上使用Apache服务器实现防盗链,可以通过配置Apache的mod_rewrite
模块来实现。以下是详细的步骤:
首先,确保你的Ubuntu系统上已经安装了Apache服务器和mod_rewrite
模块。
sudo apt update
sudo apt install apache2
sudo a2enmod rewrite
编辑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>
保存并关闭文件后,重启Apache服务器以使配置生效。
sudo systemctl restart apache2
现在,你可以测试防盗链是否生效。尝试从其他域名访问你的图片资源,应该会收到403 Forbidden错误。
通过以上步骤,你可以在Ubuntu上使用Apache服务器实现防盗链功能。