在 CentOS 系统中,Apache2 服务器可以通过配置 .htaccess
文件或直接修改 Apache 配置文件来实现防盗链功能。以下是两种方法的详细步骤:
.htaccess
文件创建或编辑 .htaccess
文件:
在你的网站根目录下创建一个 .htaccess
文件(如果已经存在则直接编辑),并添加以下内容:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
</IfModule>
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查请求的来源是否不是你的域名(忽略大小写)。RewriteCond %{HTTP_REFERER} !^$
:确保请求的来源不是空。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
:如果条件匹配,则返回 403 Forbidden 状态码,并停止进一步处理。保存并关闭 .htaccess
文件。
编辑 Apache 配置文件:
打开 Apache 的主配置文件,通常位于 /etc/httpd/conf/httpd.conf
或 /etc/apache2/apache2.conf
,具体路径取决于你的 CentOS 版本。
sudo vi /etc/httpd/conf/httpd.conf
添加防盗链配置:
在配置文件中找到 <Directory>
或 <Location>
块,添加以下内容:
<Directory "/var/www/html">
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
</Directory>
解释:
RewriteEngine On
:启用重写引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:检查请求的来源是否不是你的域名(忽略大小写)。RewriteCond %{HTTP_REFERER} !^$
:确保请求的来源不是空。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
:如果条件匹配,则返回 403 Forbidden 状态码,并停止进一步处理。保存并关闭配置文件。
重启 Apache 服务: 使配置生效,需要重启 Apache 服务:
sudo systemctl restart httpd
或者
sudo systemctl restart apache2
确保你的服务器启用了 mod_rewrite
模块。可以通过以下命令启用:
sudo a2enmod rewrite
或者
sudo systemctl enable mod_rewrite
防盗链配置中的域名应替换为你自己的域名。
防盗链规则可以根据需要调整,例如添加更多的文件类型或使用更复杂的条件。
通过以上方法,你可以在 CentOS 系统中的 Apache2 服务器上实现防盗链功能。