前提:如果图片放在阿里云服务器,那么不需要考虑图片防盗,因为阿里云有相应的服务和安全防范措施,本文是基于自己的图片服务器配置Nginx。
1、两台服务器:
- A:192.168.66.231
- B:192.168.66.232
2、Nginx 防盗链原理:
Nginx防盗链原理就是在Nginx图片服务器上,配置好自己内部服务器的所有地址,相当于放到白名单里,其他的外部地址则在访问Nginx时会被过滤掉。这样访问图片地址的时候会被拦截。
一、配置 Nginx 的防盗链
1、修改 nginx.conf 配置文件 vim /usr/local/nginx/conf/nginx.conf
2、添加 server 节点
server {
listen 80;
server_name www.feipo.com;
#access_log logs/host.access.log main;
location ~* \.(jpg|png|gif)$ {
root /home/resources;
valid_referers none server_names *.po1.com ~\.po2\.;
if ($invalid_referer){
rewrite ^/ http://xingganfeipo.com/blog/20171028/214345352.png;
}
}
}
解释:
location ~* \.(jpg|png|gif)$
作用:匹配以 jpg/png/gif 结尾的文件请求, 如果匹配就执行 括号内的代码。
valid_referers none server_names *.test1.com ~\.test2\.;
if ($invalid_referer){
rewrite ^/ http://ojt4b2cr5.bkt.clouddn.com/blog/20171028/214345352.png;
}
valid_referers none 的作用是配置可以识别的refer,就是加入白名单的请求 refer 域名。
参数说明:
- none: 代表请求的 refer 为空,也就是直接访问,比如在浏览器中直接访问图片
www.feipo.com/feipo1.png
,直接访问时,refer 会为空。 - server_names: refer 来源包含当前的
server_name
的值。 $invalid_referer:
当请求的refer
是合法的,可以被后面任一参数所匹配,$invalid_referer
的值为0, 若不匹配则值为 1。
二、配置 html 文件
1./home
目录下创建 resources
,放入一张图片 feipo.jpg。
2.修改 nginx
安装目录下 html
中的 index.html
文件。添加一个 img 标签,src 访问上一步中的图片文件
<img src="http://www.feipo.com/feipo.png" />
3.启动 nginx
/usr/local/nginx/sbin/nginx
服务器 A 的配置完毕。
4.服务器 B 配置
- 安装好 nginx,修改 nginx.conf 配置文件, 添加两个 server
server {
listen 80;
server_name www.test1.com;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
}
server {
listen 80;
server_name www.test2.com;
location / {
root html;
index index.html index.htm;
}
}
- 修改服务器 B Nginx 安装目录下 html 目录中的 index.html 文件,同样添加 img 标签。
<img src="http://www.feipo.com/test.png" />
- 启动 服务器 B 的 Nginx
配置注意事项
- 配置资源的 location 需要在 location / 之前。
- 注意调试的时候,务必使用 Ctrl + F5 进行刷新网页,因为 nginx 会缓存图片!
测试
我上面配置的 server_name 配置的域名是 www.vcmq.com ,因此测试时,需要将我电脑的 host 指向虚拟机的 ip
# 指向服务器A
192.168.66.231 www.feipo.com
# 指向服务器B
192.168.66.232 www.feipo1.com www.feipo2.com
- 浏览器访问 www.vcmq.com,图片正常加载
- 浏览器访问
www.feipo1.com
与www.feipo2.com
还有直接访问图片http://www.feipo.com/feipo.png
都正常加载
修改 服务器 A 的 nginx.conf 配置文件
valid_referers none server_names *.feipo1.com ~\.feipo2\.;
将此行修改为
valid_referers none server_names;
即只允许当前 server_name 与 无 refer 的请求,其他请求都返回 rewrite 的图片, 然后重启 nginx
/usr/local/nginx/sbin/nginx -s reload
再次分别访问
www.feipo.com
、www.feipo1.com
、www.feipo2.com
、http://www.feipo.com/feipo.png
。
发现只有 www.feipo.com
与 http://www.feipo.com/feipo.png
正常显示,其他请求皆返回 rewrite 的图片
同理再次修改 nginx.conf 文件, 允许来自 test1 的访问请求
valid_referers none server_names *.feipo1.com;
结果发现www.feipo1.com
可以获取正常图片,而www.feipo2.com
还是 rewrite 之后的图片
至此,已经实现了基于 Nginx 的简单图片防盗链。