Nginx网站如何设置防盗链?

今天在一台Ubuntu Linux下搭建了一个图床,因为不想让别的网站盗用从而浪费掉服务器资源,所以特意通过设置Nginx从而达到防盗链的功能。

其实配置很简单,只需编辑nginx的配置文件,在server字段加入如下图代码即可:

你也可以直接拷贝如下代码到你的配置文件,只需修改valid_referers部份的域名为你的域名即可:

1
2
3
4
5
6
7
8
location ~* \.(gif|jpg|png|jpeg|bmp|swf|m3u8)$ {
    expires     30d;
    valid_referers *.itkylin.com www.itkylin.com *.baidu.com *.google.com;
    if ($invalid_referer) {
    rewrite ^/ https://www.itkylin.com;
    #return 404;
	}
    }

加完代码保持退出,然后重新启动nginx服务,命令如下(Ubuntu系统下):

1
[email protected]:~# service nginx restart

更新:
(1)使用命令测试:

1
[email protected]:~# curl -e "http://www.baidu.com/1.txt" -x127.0.0.1:80 -I www.itkylin.com/test/index.m3u8

HTTP/1.1 403 Forbidden
Server: nginx
Date: Wed, 17 Oct 2018 01:20:25 GMT
Content-Type: text/html
Content-Length: 162
Connection: keep-alive

(2)nginx配置参考:

1
2
3
4
5
6
7
location ~* ^.+\.(gif|jpg|png|swf|flv|rar|zip|doc|pdf|gz|bz2|jpeg|ts|m3u8)$ {
        expires 7d;
        valid_referers none blocked server_names *.itkylin.com;
        if ($invalid_referer) {
        return 403;
        }
    }