Nginx如何防止盗链【附代码】

今天爱分享给大家带来Nginx如何防止盗链【附代码】,希望能够帮助到大家。

Nginx防盗链
配置Nginx防盗链和配置过期时间、不记录日志都用到location,所以可以把两部分写在一起,如下所示:

[root@minglinux-01 ~] vim /usr/local/nginx/conf/vhost/test.com.conf
···
 12     location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|bmp|xls)$ 
//~* 表示后面的关键词不区分大小写
 13     {
 14           expires      7d;
 15           valid_referers none blocked server_names *.test.com ;
 16           if ($invalid_referer) {   //$invalid referer表示无效的referer
 17           return 403;
 18           }
 19           access_log off;
 20     }
···

测试结果:

[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -t
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@minglinux-01 ~] /usr/local/nginx/sbin/nginx -s reload
[root@minglinux-01 ~] curl -x127.0.0.1:80 -e "http://www.baidu.com" test.com/1.gif -I
HTTP/1.1 403 Forbidden
Server: nginx/1.12.2
Date: Wed, 28 Nov 2018 13:02:18 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
[root@minglinux-01 ~] curl -x127.0.0.1:80 -e "http://www.test.com" test.com/1.gif -I
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Wed, 28 Nov 2018 13:02:25 GMT
Content-Type: image/gif
Content-Length: 2
Last-Modified: Tue, 27 Nov 2018 15:00:53 GMT
Connection: keep-alive
ETag: "5bfd5c25-2"
Expires: Wed, 05 Dec 2018 13:02:25 GMT
Cache-Control: max-age=604800
Accept-Ranges: bytes

人已赞赏
Nginx

Nginx配置文件nginx.conf详解 nginx的变量规则【附代码详解】

2020-10-19 18:10:43

Nginx

Nginx如何根据正则匹配来限制访问【附代码】

2020-10-20 17:31:52

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
'); })();