如何实现Nginx的防盗链功能?

Nginx

1 前言

为了避免博客的图片等资源被盗链而增加网络开销,笔者需要实现防盗链功能。

2 实践部分

2.1 基础环境搭建

请参阅下文搭建http与https的LNMP环境,如果你已经有此环境,请直接跳过。
https://www.cmdschool.org/archives/1

2.2 配置防盗链

2.2.1 创建防盗链规则

mkdir /etc/nginx/global/
vim /etc/nginx/global/anti-theft-chain.conf

加入如下配置:

location ~* \.(gif|jpg|png|webp)$ {
    root /var/www/www.cmdschool.org;
    valid_referers none blocked server_names
                                *.cmdschool.org cmdschool.*
                                ~\.google\. ~\.baidu\. ~\.sogou\.;
    if ($invalid_referer) {
        return 403;
        #rewrite ^/ http://www.cmdschool.org/403.jpg;
    }
}

注:留意”root”指令的配置(由于server{}标签没有定义root)

2.2.2 引用防盗链规则

vim /etc/nginx/conf.d/www.cmdschool.org_80.conf

将80端口的http服务配置文件修改如下:

server {
    listen       80;
    server_name  www.cmdschool.org;

    location / {
        root   /var/www/www.cmdschool.org;
        index  index.php;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }

    #引用防盗链规则
    include global/anti-theft-chain.conf;
}

注:综合之前的配置,配置文件的三个location优先级别请参考下表,

“=”精确匹配
“^~”不做模式匹配
“~”正则表达式的模式匹配
“~*”正则表达式的模式匹配
“” 无符号匹配模式

2.2.3 重载或重启服务

systemctl reload nginx

2.2.4 测试防盗链

2.2.4.1 向服务发送头Referer头模拟从百度引用图片链接

curl -I https://www.cmdschool.org/wp-content/uploads/2017/12/Nginx.png -H 'Referer:http://www.baidu.com'

信息显示如下:

HTTP/1.1 200 OK
Server: nginx/1.12.1
Date: Tue, 12 Dec 2017 05:18:40 GMT
Content-Type: image/png
Content-Length: 33308
Last-Modified: Sun, 10 Dec 2017 03:35:31 GMT
Connection: keep-alive
ETag: "5a2cab83-821c"
Accept-Ranges: bytes

2.2.4.2 向服务发送头Referer头模拟从QQ引用图片链接

curl -I https://www.cmdschool.org/wp-content/uploads/2017/12/Nginx.png -H 'Referer:http://www.qq.com'

信息显示如下:

HTTP/1.1 403 Forbidden
Server: nginx/1.12.1
Date: Tue, 12 Dec 2017 05:18:57 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive

==================================
参阅文档:
http://nginx.org/en/docs/http/ngx_http_referer_module.html
https://www.codeday.top/2017/07/05/27533.html
https://www.cnblogs.com/limeng951/p/5833790.html

没有评论

发表评论

Nginx
如何设置Nginx HTTP-only Cookie?

1 基础知识 1.1 HTTP cookies 1.1.1 HTTP cookies的概念 &#82 …

Nginx
如何附加Nginx Cookie标签模块?

1 基础知识 “nginx_cookie_flag_module”为上游响应标头中的cookie设置 …