防盗链配置

1. 防盗链配置

配置要点

  • none : 允许没有http_refer的请求访问资源;
  • blocked : 允许不是http://开头的,不带协议的请求访问资源;
  • 119.28.190.215 : 只允许指定ip来的请求访问资源;
location ~ .*.(jpg|gif|png)$ {
    valid_referers none blocked 119.28.190.215;
    if ($invalid_referer) {
        return 403;
    }
    root  /opt/app/code/images;
}

2. 重载nginx服务

[root@localhost ~]# nginx -s reload -c /etc/nginx/nginx.conf

3. 测试防盗链

3.1 不带http_refer

[root code]# curl -I http://119.28.190.215/1.jpg
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 30 Nov 2017 18:26:10 GMT
Content-Type: image/jpeg
Content-Length: 68227
Last-Modified: Thu, 30 Nov 2017 17:46:19 GMT
Connection: keep-alive
ETag: "5a2043eb-10a83"
Accept-Ranges: bytes

3.2 带非法http_refer

[root code]# curl -e "http://www.baidu.com" -I http://119.28.190.215/1.jpg
HTTP/1.1 403 Forbidden
Server: nginx/1.12.2
Date: Thu, 30 Nov 2017 18:25:52 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

3.3 带合法http_refer

[root code]# curl -e "http://119.28.190.215" -I http://119.28.190.215/1.jpg
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Thu, 30 Nov 2017 18:27:30 GMT
Content-Type: image/jpeg
Content-Length: 68227
Last-Modified: Thu, 30 Nov 2017 17:46:19 GMT
Connection: keep-alive
ETag: "5a2043eb-10a83"
Accept-Ranges: bytes

4. 其他配置

4.1 匹配域名

location ~ .*.(jpg|gif|png)$ {
    valid_referers ~/google./;
    if ($invalid_referer) {
        return 403;
    }
    root  /opt/app/code/images;
}
原文地址:https://www.cnblogs.com/LoveShare/p/12972076.html