實驗環(huán)境
•一臺最小化安裝的CentOS 7.3虛擬機
•配置:1核心/512MB
•nginx版本1.12.2
一、配置盜鏈網(wǎng)站
1.啟動一臺nginx虛擬機,配置兩個網(wǎng)站
vim /etc/nginx/conf.d/vhosts.conf
添加以下內容
server {
listen 80;
server_name site1.test.com;
root /var/wwwroot/site1;
index index.html;
location / {
}
}
server {
listen 80;
server_name site2.test.com;
root /var/wwwroot/site2;
index index.html;
location / {
}
}

2.在宿主機編輯C:\Windows\System32\drivers\etc\hosts文件
192.168.204.11 site1.test.com
192.168.204.11 site2.test.com
3.創(chuàng)建網(wǎng)站根目錄
mkdir /var/wwwroot
cd /var/wwwroot
mkdir site1
mkdir site2
echo -e "<h1>site1</h1><img src='1.jpg'>" >> site1/index.html
echo -e "<h1>site2</h1><img src='http://site1.test.com/1.jpg'>" >> site2/index.html
4.將1.jpg上傳到/var/wwwroot/site1目錄
5.啟動nginx服務
systemctl restart nginx
netstat -anpt | grep nginx

6.防火墻放通80端口
setenforce 0
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
7.在宿主機訪問
http://site1.test.com

http://site2.test.com

二、配置site1.test.com防盜鏈
1.編輯nginx配置文件
server {
listen 80;
server_name site1.test.com;
root /var/wwwroot/site1;
index index.html;
location / {
}
location ~ \.(jpg|png|gif|jpeg)$ {
valid_referers site1.test.com;
if ($invalid_referer) {
return 403;
}
}
}
server {
listen 80;
server_name site2.test.com;
root /var/wwwroot/site2;
index index.html;
location / {
}
}

2.重啟nginx服務
systemctl restart nginx
3.在宿主機訪問
清除瀏覽器緩存,訪問http://site1.test.com

清除瀏覽器緩存,訪問http://site2.test.com

可見,防盜鏈配置起到了作用
三、配置防盜鏈返回其他資源
1.編輯nginx配置文件
增加一個虛擬主機,對防盜鏈保護的資源進行重寫
server {
listen 80;
server_name site1.test.com;
root /var/wwwroot/site1;
index index.html;
location / {
}
location ~ \.(jpg|png|gif|jpeg)$ {
valid_referers site1.test.com;
if ($invalid_referer) {
rewrite ^/ http://site3.test.com/notfound.jpg;
#return 403;
}
}
}
server {
listen 80;
server_name site2.test.com;
root /var/wwwroot/site2;
index index.html;
location / {
}
}
server {
listen 80;
server_name site3.test.com;
root /var/wwwroot/site3;
index index.html;
location / {
}
}
解釋
location ~ \.(jpg|png|gif|jpeg)$ {}為設置防盜鏈的文件類型,使用豎線|分隔。
valid_referers site1.test.com *.nginx.org;為白名單,使用空格分隔,可以使用*進行泛域名設置。
if ($invalid_referer) {}為判斷是否符合白名單,不符合白名單將執(zhí)行{}內的內容。
rewrite ^/ http://site3.test.com/notfound.jpg;為重寫資源,如果不合符白名單,則重寫為該地址。
return 403;代表返回的狀態(tài)碼為403。
2.建立site3根目錄
cd /var/wwwroot
mkdir site3
echo -e "<h1>site3</h1><img src='notfound.jpg'>" >> site3/index.html
3.上傳notfound.jpg文件至/var/wwwroot/site3目錄
4.重啟nginx服務
systemctl restart nginx
5.在宿主機編輯C:\Windows\System32\drivers\etc\hosts文件
增加對site3.test.com的映射
192.168.204.11 site1.test.com
192.168.204.11 site2.test.com
192.168.204.11 site3.test.com
6.在宿主機訪問http://site2.test.com
可以看到,在site2中盜用的site1的1.jpg文件,被重定向到了site3上的notfound.jpg文件

總結
以上所述是小編給大家介紹的配置Nginx的防盜鏈的操作方法 ,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請注明出處,謝謝!