目录
一、什么是防盗链
防盗链是一种保护网站资源不被其他网站非法链接的技术。防止外部网站通过直接链接的方式引用你的图片、视频、CSS文件或其他静态资源。从而避免不必要的带宽消耗和服务器负载。检查HTTP请求头中的 Referer 字段、以确定请求是否来自合法的来源。如果 Referer 不在白名单中,则拒绝提供资源或返回一个代替的内容。
二、防盗链演示
(一)准备工作
1. 准备两台虚拟机,都能与主机互通。
2.虚拟机1(192.168.80.100)配置
(1)准备一个静态页面(默认即可)和一个img文件夹(文件夹下放一张图片)
(2)index文件加上图片跳转链接
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!192.168.80.100</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
<a href="http://192.168.80.100/img/1.png">img</a>
</body>
</html>
(3)修改Nginx.conf配置文件
worker_processes 1;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
#proxy_pass http://httpds;
root html;
index index.html index.htm;
}
location ~*/(js|img|css) {
valid_referers 192.168.80.100;
if ($invalid_referer){
return 403;
}
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
通过 valid_referers 用于定义哪些来源(即 Referer
头中的 URL)是允许访问特定资源的,这里定义只有通过192.168.80.100访问才能获取图片资源。更改nginx.conf需要重启nginx。
(4)通过第一台虚拟机访问静态资源
点击img访问图片资源(此时的referer是192.168.80.100)
3. 虚拟机2(192.168.80.101)配置
(1)准备一个静态页面,在里面放一个访问第一台虚拟机图片的链接
(2)编写index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!192.168.80.101</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
<a href="http://192.168.80.100/img/1.png">img</a>
</body>
</html>
(3)第二台虚拟机nginx.conf文件配置
#user nobody;
worker_processes 1;
#pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
(4)访问
(二)演示
这里访问192.168.80.101,点击img访问第一台虚拟机nginx上的静态资源。发现返回403。
由于在第一台虚拟机的nginx上设置了 valid_referers,所以192.168.80.100上的静态资源不允许外部网站引用。
valid_referers 192.168.80.100;