在Ubuntu下配置Apache防盜鏈,可以通過修改Apache的配置文件來實現。以下是具體的步驟:
mod_rewrite
模塊啟用mod_rewrite
模塊
打開終端,運行以下命令啟用mod_rewrite
模塊:
sudo a2enmod rewrite
重啟Apache服務 使更改生效,重啟Apache服務:
sudo systemctl restart apache2
編輯.htaccess
文件
在需要防盜鏈的目錄下創建或編輯.htaccess
文件。例如,如果你想保護/var/www/html/images
目錄下的圖片,可以在該目錄下創建一個.htaccess
文件。
nano /var/www/html/images/.htaccess
添加防盜鏈規則
在.htaccess
文件中添加以下內容:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
解釋:
RewriteEngine On
:啟用重寫引擎。RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
:檢查HTTP請求頭中的Referer
字段,如果不是來自你的域名(yourdomain.com
),則執行下一步。RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
:阻止訪問指定的圖片文件類型(如.jpg
, .jpeg
, .png
, .gif
),返回403 Forbidden狀態碼。mod_security
模塊如果你已經安裝了mod_security
模塊,可以使用它來配置防盜鏈。
啟用mod_security
模塊
打開終端,運行以下命令啟用mod_security
模塊:
sudo a2enmod security2
重啟Apache服務 使更改生效,重啟Apache服務:
sudo systemctl restart apache2
編輯mod_security.conf
文件
打開mod_security
的配置文件:
sudo nano /etc/modsecurity/modsecurity.conf
添加防盜鏈規則 在文件中添加以下規則:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif)$" \
"id:123456,\
phase:2,\
deny,\
status:403,\
log,\
msg:'Access to images is denied from external sites',\
chain"
SecRule REQUEST_HEADERS:Referer "!@rx ^http://(www\.)?yourdomain\.com$" \
"t:none"
解釋:
SecRule REQUEST_FILENAME "\.(jpg|jpeg|png|gif)$"
:匹配請求的文件名是否為圖片文件。id:123456
:規則的唯一標識符。phase:2
:規則執行的階段。deny
:拒絕訪問。status:403
:返回403 Forbidden狀態碼。log
:記錄日志。msg:'Access to images is denied from external sites'
:日志消息。chain
:鏈式規則。SecRule REQUEST_HEADERS:Referer "!@rx ^http://(www\.)?yourdomain\.com$"
:檢查Referer
頭是否不是來自你的域名。重啟Apache服務 使更改生效,重啟Apache服務:
sudo systemctl restart apache2
通過以上兩種方法,你可以在Ubuntu下配置Apache防盜鏈,保護你的資源不被非法訪問。