在Ubuntu上配置Apache防盗链,可以通过修改Apache的配置文件来实现。以下是详细的步骤:
如果你还没有安装Apache,可以使用以下命令进行安装:
sudo apt update
sudo apt install apache2
你可以使用mod_rewrite
模块来创建防盗链规则。首先,确保mod_rewrite
模块已经启用:
sudo a2enmod rewrite
然后重启Apache服务以应用更改:
sudo systemctl restart apache2
编辑你的网站配置文件。通常,这些文件位于/etc/apache2/sites-available/
目录下。例如,如果你的网站配置文件是yourdomain.com.conf
,你可以使用以下命令编辑它:
sudo nano /etc/apache2/sites-available/yourdomain.com.conf
在<VirtualHost>
块中添加以下内容:
<VirtualHost *:80>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
# 允许的域名列表
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查HTTP Referer是否不是你的域名(不区分大小写)。RewriteCond %{HTTP_REFERER} !^$
:检查Referer是否为空。RewriteRule \.(jpg|jpeg|png|gif)$ - [F]
:如果Referer不符合条件,则返回403 Forbidden状态码。按Ctrl + X
,然后按Y
确认保存,最后按Enter
退出编辑器。
为了使更改生效,重启Apache服务:
sudo systemctl restart apache2
你可以通过尝试从其他域名访问你的图片资源来测试防盗链是否生效。如果防盗链配置正确,你应该会看到403 Forbidden错误。
通过以上步骤,你就可以在Ubuntu上配置Apache防盗链了。根据你的具体需求,你可以调整允许的域名列表和文件类型。