在Ubuntu上使用Apache服務器實現防盜鏈,可以通過配置Apache的mod_rewrite
模塊來實現。以下是詳細的步驟:
首先,確保你的Ubuntu系統上已經安裝了Apache服務器和mod_rewrite
模塊。
sudo apt update
sudo apt install apache2
sudo a2enmod rewrite
編輯Apache的配置文件或網站的虛擬主機配置文件。通常,這些文件位于/etc/apache2/sites-available/
目錄下。
如果你希望對所有網站生效,可以編輯/etc/apache2/apache2.conf
文件。
sudo nano /etc/apache2/apache2.conf
在文件的末尾添加以下內容:
<Directory "/var/www/html">
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
</Directory>
將yourdomain.com
替換為你的實際域名。
如果你只想對特定網站生效,可以編輯該網站的虛擬主機配置文件。例如,如果你的網站配置文件是/etc/apache2/sites-available/yourdomain.com.conf
,則編輯該文件:
sudo nano /etc/apache2/sites-available/yourdomain.com.conf
在<VirtualHost *:80>
塊中添加以下內容:
<VirtualHost *:80>
ServerAdmin webmaster@yourdomain.com
DocumentRoot /var/www/html
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?yourdomain\.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [F,L]
</VirtualHost>
保存并關閉文件后,重啟Apache服務器以使配置生效。
sudo systemctl restart apache2
現在,你可以測試防盜鏈是否生效。嘗試從其他域名訪問你的圖片資源,應該會收到403 Forbidden錯誤。
通過以上步驟,你可以在Ubuntu上使用Apache服務器實現防盜鏈功能。