在Ubuntu下配置Apache防盗链,可以通过修改Apache的配置文件来实现。以下是具体的步骤:
mod_rewrite
模块启用mod_rewrite
模块
打开终端,运行以下命令启用mod_rewrite
模块:
sudo a2enmod rewrite
重启Apache服务 使更改生效,重启Apache服务:
sudo systemctl restart apache2
编辑.htaccess
文件
在需要防盗链的目录下创建或编辑.htaccess
文件。例如,如果你想保护/var/www/html/images
目录下的图片,可以在该目录下创建一个.htaccess
文件。
nano /var/www/html/images/.htaccess
添加防盗链规则
在.htaccess
文件中添加以下内容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查HTTP请求头中的Referer
字段,如果不是来自你的域名(yourdomain.com
),则执行下一步。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
:阻止访问指定的图片文件类型(如.jpg
, .jpeg
, .png
, .gif
),返回403 Forbidden状态码。mod_security
模块如果你已经安装了mod_security
模块,可以使用它来配置防盗链。
启用mod_security
模块
打开终端,运行以下命令启用mod_security
模块:
sudo a2enmod security2
重启Apache服务 使更改生效,重启Apache服务:
sudo systemctl restart apache2
编辑mod_security.conf
文件
打开mod_security
的配置文件:
sudo nano /etc/modsecurity/modsecurity.conf
添加防盗链规则 在文件中添加以下规则:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif)$" \
"id:123456,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Access to images is denied from external sites',\
chain"
SecRule REQUEST_HEADERS:Referer "!@rx ^http://(www\.)?yourdomain\.com$" \
"t:none"
解释:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif)$"
:匹配请求的文件名是否为图片文件。id:123456
:规则的唯一标识符。phase:2
:规则执行的阶段。deny
:拒绝访问。status:403
:返回403 Forbidden状态码。log
:记录日志。msg:'Access to images is denied from external sites'
:日志消息。chain
:链式规则。SecRule REQUEST_HEADERS:Referer "!@rx ^http://(www\.)?yourdomain\.com$"
:检查Referer
头是否不是来自你的域名。重启Apache服务 使更改生效,重启Apache服务:
sudo systemctl restart apache2
通过以上两种方法,你可以在Ubuntu下配置Apache防盗链,保护你的资源不被非法访问。