本文介绍如何通过修改apache配置文件(通常为httpd.conf或apache2.conf)来启用防盗链功能。
步骤一:定位并打开Apache配置文件
首先,找到并打开你的Apache配置文件。文件位置通常为/etc/httpd/conf/(centos/RHEL系统)或/etc/apache2/(debian/ubuntu系统)。使用以下命令打开:
sudo nano /etc/httpd/conf/httpd.conf # CentOS/RHEL # 或 sudo nano /etc/apache2/apache2.conf # Debian/Ubuntu
步骤二:启用mod_rewrite模块
确保已启用mod_rewrite模块。这可以通过以下命令实现:
sudo a2enmod rewrite # Debian/Ubuntu # 或 sudo systemctl enable rewrite # CentOS/RHEL
步骤三:添加防盗链规则
在Apache配置文件的
方法一:使用.htaccess文件
在网站根目录创建或编辑.htaccess文件:
sudo nano /var/www/html/.htaccess
添加以下内容:
RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com [NC] RewriteCond %{HTTP_REFERER} !^$ RewriteRule .(jpg|jpeg|png|gif)$ - [F]
方法二:使用
在主配置文件中,在
<VirtualHost *:80> ServerName yourdomain.com DocumentRoot /var/www/html <Directory /> RewriteEngine On RewriteCond %{HTTP_REFERER} !^http://(www.)?yourdomain.com [NC] RewriteCond %{HTTP_REFERER} !^$ RewriteRule .(jpg|jpeg|png|gif)$ - [F] </Directory> </VirtualHost>
请将yourdomain.com替换为你的实际域名。
步骤四:重启Apache服务器
保存配置文件后,重启Apache服务器使更改生效:
sudo systemctl restart apache2 # Debian/Ubuntu # 或 sudo systemctl restart httpd # CentOS/RHEL
步骤五:测试防盗链功能
尝试从其他域名访问你的图片,确认防盗链规则是否生效。如果配置正确,你将收到403 Forbidden错误。
通过以上步骤,即可完成Apache防盗链配置。 可根据实际需求调整规则以适应不同场景。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END