Nginx 防盗链问题
两个网站 A 和 B, B网站引用了A网站上的图片,这种行为就叫做盗链。 防盗链,就是要防止B引用A的图片。
HTTP Referer是Header的一部分,当浏览器向Web服务器发送请求的时候,一般会带上Referer,告诉服务器我是从哪个页面链接过来的,服务器借此可以获得一些信息用于处理,例如防止未经允许的网站盗链图片、文件等。因此HTTP Referer头信息是可以通过程序来伪装生成的,所以通过Referer信息防盗链并非100%可靠,但是,它能够限制大部分的盗链情况。
1、图片网站服务器搭建
[root@nginx-server ~]# cp test.jpg /usr/share/nginx/html/
[root@nginx-server ~]# cd /etc/nginx/conf.d/
[root@nginx-server conf.d]# cp default.conf default.conf.bak
[root@nginx-server conf.d]# mv default.conf nginx.conf
修改nginx配置文件
#vim nginx.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
重启Nginx,访问测试(注意后缀)
2、盗链机器配置
1、修改Nginx配置文件
#vim /etc/nginx/conf.d/qf.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
[root@nginx-client ~]# cd /usr/share/nginx/html/
[root@nginx-client html]# cp index.html index.html.bak
[root@nginx-client html]# vim index.html
# vim index.html //编写访问界面
<html>
<head>
<meta charset="utf-8">
<title>qf.com</title>
</head>
<body style="background-color:red;">
<img src="http://192.168.88.154/test.jpg"/>
</body>
</html>
访问测试 :此时盗链机已成功完成跳转
3、在图片服务器操作
# vim nginx.conf
server {
listen 80;
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
valid_referers none blocked www.jd.com; #允许这些访问
if ($invalid_referer) {
return 403;
}
}
}
重启nginx
# systemctl restart nginx
访问此时:此时防盗链已完成了