配置Apache防盜鏈可以通過修改Apache的配置文件來實現。防盜鏈的目的是防止其他網站未經授權地引用你的圖片、視頻或其他資源。以下是一個基本的步驟指南:
mod_rewrite模塊啟用mod_rewrite模塊:
確保你的Apache服務器已經啟用了mod_rewrite模塊。你可以在終端或命令提示符中運行以下命令來啟用它:
sudo a2enmod rewrite
然后重啟Apache服務器:
sudo systemctl restart apache2
編輯.htaccess文件:
在你的網站根目錄下創建或編輯.htaccess文件。這個文件允許你定義URL重寫規則。
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif|swf)$ - [F,L]
</IfModule>
解釋:
RewriteEngine On:啟用重寫引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]:檢查HTTP請求頭中的Referer字段,如果不是來自你的域名,則拒絕訪問。RewriteRule \.(jpg|jpeg|png|gif|swf)$ - [F,L]:匹配圖片和視頻文件,并返回403 Forbidden狀態碼。mod_headers模塊啟用mod_headers模塊:
確保你的Apache服務器已經啟用了mod_headers模塊。你可以在終端或命令提示符中運行以下命令來啟用它:
sudo a2enmod headers
然后重啟Apache服務器:
sudo systemctl restart apache2
編輯.htaccess文件:
在你的網站根目錄下創建或編輯.htaccess文件。
<IfModule mod_headers.c>
SetEnvIf Referer "^$" dontlog
SetEnvIf Referer ".*yourdomain\.com" dontlog
SetEnvIf Referer ".*yourdomain\.com.*" dontlog
Header set X-Robots-Tag "noindex, nofollow" env=dontlog
Header set Content-Security-Policy "default-src 'self'; img-src 'self' data:; script-src 'self';"
</IfModule>
解釋:
SetEnvIf Referer "^$" dontlog:設置一個環境變量dontlog,如果Referer為空(即直接訪問)。SetEnvIf Referer ".*yourdomain\.com" dontlog:設置一個環境變量dontlog,如果Referer來自你的域名。SetEnvIf Referer ".*yourdomain\.com.*" dontlog:設置一個環境變量dontlog,如果Referer包含你的域名。Header set X-Robots-Tag "noindex, nofollow" env=dontlog:設置X-Robots-Tag頭,防止搜索引擎索引這些資源。Header set Content-Security-Policy "default-src 'self'; img-src 'self' data:; script-src 'self';":設置內容安全策略,限制資源的來源。.htaccess文件位于正確的目錄下,并且Apache配置允許使用.htaccess文件進行重寫和頭信息設置。.htaccess文件。在這種情況下,你可以聯系你的主機提供商尋求幫助。通過以上步驟,你可以有效地配置Apache防盜鏈,保護你的網站資源不被未經授權的引用。