在 CentOS 系統上,Apache 服務器可以通過配置 .htaccess
文件來實現防盜鏈功能。以下是一些常用的防盜鏈方法:
使用 mod_rewrite
模塊:
在需要防盜鏈的目錄下創建或編輯 .htaccess
文件,添加以下內容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
將 yourdomain.com
替換為你自己的域名。這段代碼會檢查訪問者的 HTTP_REFERER,如果不是來自你指定的域名,將拒絕訪問圖片文件。
使用 mod_authz_core
和 mod_authz_host
模塊:
在 Apache 配置文件(如 /etc/httpd/conf/httpd.conf
或 /etc/httpd/conf.d/yourdomain.conf
)中添加以下內容:
<Directory "/path/to/your/protected/directory">
AuthType Basic
AuthName "Restricted Content"
AuthUserFile /etc/httpd/.htpasswd
Require host yourdomain.com
</Directory>
將 /path/to/your/protected/directory
替換為你需要保護的目錄路徑,將 yourdomain.com
替換為你自己的域名。這段代碼會要求訪問者使用指定的用戶名和密碼才能訪問該目錄下的內容。
使用第三方模塊 mod_security:
安裝 mod_security 模塊:
sudo yum install mod_security
啟用 mod_security 模塊:
sudo systemctl enable mod_security
sudo systemctl start mod_security
在 Apache 配置文件(如 /etc/httpd/conf/httpd.conf
或 /etc/httpd/conf.d/yourdomain.conf
)中添加以下內容:
<Location "/path/to/your/protected/directory">
SecRule REQUEST_URI "@endsWith .(jpg|jpeg|png|gif)$" \
"id:1234567,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Access to images is restricted'"
</Location>
將 /path/to/your/protected/directory
替換為你需要保護的目錄路徑。這段代碼會拒絕訪問指定目錄下的圖片文件。
注意:在進行上述操作之前,請確保已經備份了相關配置文件,以便在出現問題時可以恢復。