Nginx 如何配置防盗链
原创标题:Nginx 怎样配置防盗链
随着互联网的逐步发展中,网站防盗链变得越来越重要。防盗链可以防止其他网站非法盗用你的图片、视频等资源,从而保护你的网站版权。Nginx 作为一款高性能的 Web 服务器,也提供了充裕的配置选项来帮助用户实现防盗链功能。本文将详细介绍怎样配置 Nginx 防盗链。
一、了解防盗链
防盗链(Hotlink Prevention)是指防止其他网站直接从你的服务器上加载资源(如图片、视频等),而是通过你的网站链接进行访问。这样,用户在访问你的网站时,可以首先看到你的网站内容,然后再跳转到其他网站加载资源。防盗链的核心目的是保护你的网站资源不被其他网站非法盗用。
二、Nginx 防盗链配置
在 Nginx 中,可以通过配置 `location` 块来实现防盗链功能。以下是一些常用的配置方法:
1. 使用 `valid_referers` 指令
`valid_referers` 指令可以局限哪些网站的链接是有效的。如果请求的链接不是由指定的网站发出的,则返回 403 状态码,实现防盗链。
location ~* \.(jpg|jpeg|gif|png|swf|flv)$ {
valid_referers www.example.com example.com;
if ($invalid_referer) {
return 403;
}
expires 30d;
add_header Cache-Control "public";
}
在上面的配置中,只有来自 `www.example.com` 和 `example.com` 的链接是有效的。如果请求的链接不是由这两个网站发出的,则返回 403 状态码。
2. 使用 `proxy_set_header` 指令
`proxy_set_header` 指令可以修改请求头中的 `Referer` 字段,从而实现防盗链。
location ~* \.(jpg|jpeg|gif|png|swf|flv)$ {
proxy_set_header Referer $http_referer;
if ($http_referer ~* ^http://(www\.example\.com|example\.com)) {
expires 30d;
add_header Cache-Control "public";
} else {
return 403;
}
}
在上面的配置中,只有当请求头中的 `Referer` 字段包含 `http://www.example.com` 或 `http://example.com` 时,才会返回资源。否则,返回 403 状态码。
3. 使用 `if` 指令结合 `valid_referers` 和 `proxy_set_header`
将 `valid_referers` 和 `proxy_set_header` 结合使用,可以更精确地控制防盗链。
location ~* \.(jpg|jpeg|gif|png|swf|flv)$ {
valid_referers www.example.com example.com;
if ($invalid_referer) {
return 403;
}
proxy_set_header Referer $http_referer;
if ($http_referer ~* ^http://(www\.example\.com|example\.com)) {
expires 30d;
add_header Cache-Control "public";
} else {
return 403;
}
}
在上面的配置中,首先使用 `valid_referers` 指令局限有效链接,然后使用 `proxy_set_header` 指令修改请求头中的 `Referer` 字段。只有当请求头中的 `Referer` 字段包含 `http://www.example.com` 或 `http://example.com` 时,才会返回资源。否则,返回 403 状态码。
4. 使用 `proxy_cache` 和 `proxy_cache_path`
`proxy_cache` 和 `proxy_cache_path` 指令可以配置缓存,从而尽大概减少损耗网站访问速度。同时,结合 `valid_referers` 指令可以实现防盗链。
location ~* \.(jpg|jpeg|gif|png|swf|flv)$ {
valid_referers www.example.com example.com;
if ($invalid_referer) {
return 403;
}
proxy_cache my_cache;
proxy_cache_path /path/to/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
proxy_cache_valid 200 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_revalidate on;