在Apache服务器中,可以通过配置.htaccess
文件或直接在httpd.conf
文件中添加规则来实现防盗链功能。防盗链的主要目的是防止其他网站未经许可就使用你的图片、视频等资源。
以下是实现防盗链的几种方法:
mod_rewrite
模块启用mod_rewrite
模块(如果尚未启用):
sudo a2enmod rewrite
sudo systemctl restart apache2
编辑.htaccess
文件:
在需要防盗链的目录下创建或编辑.htaccess
文件,添加以下内容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [F,L]
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查请求的Referer是否不是你的域名(不区分大小写)。RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [F,L]
:如果条件匹配,则返回403 Forbidden状态码,并停止进一步处理。mod_headers
模块启用mod_headers
模块(如果尚未启用):
sudo a2enmod headers
sudo systemctl restart apache2
编辑.htaccess
文件:
在需要防盗链的目录下创建或编辑.htaccess
文件,添加以下内容:
<IfModule mod_headers.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [F,L]
</IfModule>
mod_authz_core
模块启用mod_authz_core
模块(如果尚未启用):
sudo a2enmod authz_core
sudo systemctl restart apache2
编辑.htaccess
文件:
在需要防盗链的目录下创建或编辑.htaccess
文件,添加以下内容:
<IfModule mod_authz_core.c>
AuthType None
AuthName "Restricted Content"
AuthUserFile /dev/null
Require valid-user
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|svg)$ - [F,L]
</IfModule>
.htaccess
文件进行重写规则。yourdomain.com
为你自己的域名。通过以上方法,你可以有效地防止其他网站未经许可就使用你的资源。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: ubuntu compton配置步骤