web服务之nginx_Rewrite 相关功能

Rewrite 相关功能

Nginx服务器利用 ngx_http_rewrite_module 模块解析和处理rewrite请求,此功能依靠 PCRE(perl
compatible regular expression),因此编译之前要安装PCRE库,rewrite是nginx服务器的重要功能之
一,用于实现URL的重写,URL的重写是非常有用的功能,比如它可以在我们改变网站结构之后,不需
要客户端修改原来的书签,也无需其他网站修改我们的链接,就可以设置为访问,另外还可以在一定程
度上提高网站的安全性。

ngx_http_rewrite_module 模块指令

官方文档: https://nginx.org/en/docs/http/ngx_http_rewrite_module.html
if 指令

官方文档:

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#if

用于条件匹配判断,并根据条件判断结果选择不同的Nginx配置,可以配置在server或location块中进行
配置,Nginx的if语法仅能使用if做单次判断,不支持使用if else或者if elif这样的多重判断,用法如下:

if (条件匹配){
    action
}

使用正则表达式对变量进行匹配,匹配成功时if指令认为条件为true,否则认为false,变量与表达式之
间使用以下符号链接:

= #比较变量和字符串是否相等,相等时if指令认为该条件为true,反之为false
!= #比较变量和字符串是否不相等,不相等时if指令认为条件为true,反之为false
~ #区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~ #区分大小写字符,判断是否匹配,不满足匹配条件为真,满足匹配条件为假
~* #不区分大小写字符,可以通过正则表达式匹配,满足匹配条件为真,不满足匹配条件为假
!~* #不区分大小字符,判断是否匹配,满足匹配条件为假,不满足匹配条件为真
-f 和 !-f #判断请求的文件是否存在和是否不存在
-d 和 !-d #判断请求的目录是否存在和是否不存在
-x 和 !-x #判断文件是否可执行和是否不可执行
-e 和 !-e #判断请求的文件或目录是否存在和是否不存在(包括文件,目录,软链接)

#注意:
#如果$变量的值为空字符串或0,则if指令认为该条件为false,其他条件为true。
#nginx 1.0.1之前$变量的值如果以0开头的任意字符串会返回false

#示例:
location /main {
    index index.html;
    default_type text/html;
    if ( $scheme = http ){
        echo "if-----> $scheme";
    }
    if ( $scheme = https ){
        echo "if ----> $scheme";
    }
    #if (-f $request_filename) {
    # echo "$request_filename is exist";
    #}
    if (!-e $request_filename) {
       echo "$request_filename is not exist";
       #return 409;
    }
}
set 指令

指定key并给其定义一个变量,变量可以调用Nginx内置变量赋值给key,另外set定义格式为set $key
value,value可以是text, variables和两者的组合。

location /main {
    root /data/nginx/html/pc;
    index index.html;
    default_type text/html;
    set $name longxuan;
    echo $name;
    set $my_port $server_port;
    echo $my_port;
}
break 指令

用于中断当前相同作用域(location)中的其他Nginx配置,与该指令处于同一作用域的Nginx配置中,位
于它前面的配置生效,位于后面的 ngx_http_rewrite_module 模块中指令就不再执行,Nginx服务器
在根据配置处理请求的过程中遇到该指令的时候,回到上一层作用域继续向下读取配置,该指令可以在
server块和locationif块中使用
注意: 如果break指令在location块中后续指令还会继续执行,只是不执行ngx_http_rewrite_module 模
块的指令,其它指令还会执行

使用语法如下:

if ($slow) {
    limit_rate 10k;
    break;
}
location /main {
    root /data/nginx/html/pc;
    index index.html;
    default_type text/html;
    set $name longxuan;
    echo $name;
    break; #location块中break后面指令还会执行
    set $my_port $server_port;
    echo $my_port;
}
return 指令

return用于完成对请求的处理,并直接向客户端返回响应状态码,比如:可以指定重定向URL(对于特殊重
定向状态码,301/302等) 或者是指定提示文本内容(对于特殊状态码403/500等),处于此指令后的所有配置都将不被执行,return可以在server、if 和 location块进行配置

语法格式:

return code; #返回给客户端指定的HTTP状态码
return code [text]; #返回给客户端的状态码及响应报文的实体内容,可以调用变量,其中text如果有空
格,需要用单或双引号
return code URL; #返回给客户端的URL地址

范例:

location / {
    root /data/nginx/html/pc;
    default_type text/html;
    index index.html;
    if ( $scheme = http ){
        #return 666;
        #return 666 "not allow http";
        #return 301 http://www.baidu.com;
        return 500 "service error";
        echo "if-----> $scheme"; #return后面的将不再执行
    }
    if ( $scheme = https ){
        echo "if ----> $scheme";
    }
}

范例: return

location /test {
    default_type application/json;
    return 200 '{"status:"success"}';
}

范例:

server {
    listen 80;
    server_name www.longxuan.vip;
    return 301 https://$server_name$request_uri;
}
server {
    listen 443 ssl;
    server_name www.longxuan.vip;
    ssl_certificate /etc/nginx/ssl/www.longxuan.vip.crt;
    ssl_certificate_key /etc/nginx/ssl/www.longxuan.vip.key;
    location / {
        root /data/www/html;
    }
}
rewrite_log 指令

设置是否开启记录ngx_http_rewrite_module 模块日志记录到 error_log日志文件当中,可以配置在
http、server、location 或 if 中

注意: 需要日志级别为 notice

location /main {
    index index.html;
    default_type text/html;
    set $name longxuan;
    echo $name;
    rewrite_log on;
    break;
    set $my_port $server_port;
    echo $my_port;
}

#重启nginx,访问并验证error_log:
[root@centos8 ~]# tail -f /apps/nginx/logs/error.log
2020/02/27 15:10:02 [warn] 5815#0: *3 using uninitialized "my_port" variable,
client: 172.31.0.1, server: longxuan.vip, request: "GET /main HTTP/1.1", host:
"www.longxuan.vip"

rewrite 指令

通过正则表达式的匹配来改变URI,可以同时存在一个或多个指令,按照顺序依次对URI进行匹配,
rewrite主要是针对用户请求的URL或者是URI做具体处理

官方文档:

https://nginx.org/en/docs/http/ngx_http_rewrite_module.html#rewrite

rewrite可以配置在 server、location、if

语法格式 :

rewrite regex replacement [flag];

rewrite将用户请求的URI基于regex所描述的模式进行检查,匹配到时将其替换为表达式指定的新的URI

注意:如果在同一级配置块中存在多个rewrite规则,那么会自下而下逐个检查;被某条件规则替换完成
后,会重新一轮的替换检查,隐含有循环机制,但不超过10次;如果超过,提示500响应码,[flag]所表示
的标志位用于控制此循环机制
如果替换后的URL是以http://或https://开头,则替换结果会直接以重定向返回给客户端, 即永久重定向301

正则表达式格式
. #匹配除换行符以外的任意字符
\w #匹配字母或数字或下划线或汉字
\s #匹配任意的空白符
\d #匹配数字
\b #匹配单词的开始或结束
^ #匹配字付串的开始
$ #匹配字符串的结束
* #匹配重复零次或更多次
+ #匹配重复一次或更多次
? #匹配重复零次或一次
(n) #匹配重复n次
{n,} #匹配重复n次或更多次
{n,m} #匹配重复n到m次
*? #匹配重复任意次,但尽可能少重复
+? #匹配重复1次或更多次,但尽可能少重复
?? #匹配重复0次或1次,但尽可能少重复
{n,m}? #匹配重复n到m次,但尽可能少重复
{n,}? #匹配重复n次以上,但尽可能少重复
\W #匹配任意不是字母,数字,下划线,汉字的字符
\S #匹配任意不是空白符的字符
\D #匹配任意非数字的字符
\B #匹配不是单词开头或结束的位置
[^x] #匹配除了x以外的任意字符
[^longxuan] #匹配除了longxuan 这几个字母以外的任意字符
rewrite flag 使用介绍

利用nginx的rewrite的指令,可以实现url的重新跳转,rewrite有四种不同的flag,分别是redirect(临时
重定向302)、permanent(永久重定向301)、break和last。其中前两种是跳转型的flag,后两种是代理型:

● 跳转型指由客户端浏览器重新对新地址进行请求

● 代理型是在WEB服务器内部实现跳转

rewrite 格式
Syntax: rewrite regex replacement [flag]; #通过正则表达式处理用户请求并返回替换后的数据
包。
Default: —
Context: server, location, if
flag 说明
redirect;
#临时重定向,重写完成后以临时重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求;
使用相对路径,或者http://或https://开头,状态码:302
permanent;
#重写完成后以永久重定向方式直接返回重写后生成的新URL给客户端,由客户端重新发起请求,状态码:301
break;
#重写完成后,停止对当前URL在当前location中后续的其它重写操作,而后直接跳转至重写规则配置块之后
的其它配置;结束循环,建议在location中使用
#适用于一个URL一次重写
last;
#重写完成后,停止对当前URI在当前location中后续的其它重写操作,而后对新的URL启动新一轮重写检查,
不建议在location中使用
#适用于一个URL多次重写,要注意避免出现超过十次以及URL重写后返回错误的给用户

rewrite案例: 域名永久与临时重定向

域名的临时的调整,后期可能会变,之前的域名或者URL可能还用、或者跳转的目的域名和URL还会跳转,这种情况浏览器不
会缓存跳转,临时重定向不会缓存域名解析记录(A记录),但是永久重定向会缓存。

示例: 因业务需要,将访问源域名 www.longxuan.vip 的请求永久重定向到 www.longxuan.com

location / {
    root /data/nginx/html/pc;
    index index.html;
    rewrite / http://www.longxuan.com permanent;
    #rewrite / http://www.longxuan.com redirect;
}

#重启Nginx并访问域名 http://www.longxuan.vip 进行测试

永久重定向301

域名永久型调整,即域名永远跳转至另外一个新的域名,之前的域名再也不使用,跳转记录可以缓存到客户端浏览器
永久重定向会缓存DNS解析记录, 浏览器中有 from disk cache 信息,即使nginx服务器无法访问,浏览
器也会利用缓存进行重定向
比如: 京东早期的域名 www.360buy.com 由于与360公司类似,于是后期永久重定向到了 www.jd.com

临时重定向302

域名临时重定向,告诉浏览器域名不是固定重定向到当前目标域名,后期可能随时会更改,因此浏览器
不会缓存当前域名的解析记录,而浏览器会缓存永久重定向的DNS解析记录,这也是临时重定向与永久
重定向最大的本质区别。
即当nginx服务器无法访问时,浏览器不能利用缓存,而导致重定向失败

rewrite 案例: break 与 last

break 案例
#break测试案例:当客户端访问break的时候,测试通过rewrite将URL重写为test1,然后再通过
rewrite将test1重写为test2测试两条write规则最终哪一条生效,并且测试重写后的URL会不会到其他
location重新匹配
[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /break {
    #return 666 "break";
    root /data/nginx;
    index index.html;
    rewrite ^/break/(.*) /test1/$1 break;    #break匹配成功后不再向下匹配,也不会跳转到其他的location,即直接结束匹配并给客户端返回结果数据。
    rewrite ^/test1/(.*) /test2/$1 break;    #break不会匹配后面的rewrite规则也不匹配location
}

location /test1 {
    default_type text/plain;
    echo "new test1";
    return 996 "new test1";
}

location /test2 {
    default_type text/plain;
    echo "new test2";
    return 666 "new test2";
}

#创建资源路径:
[root@centos8 ~]# mkdir /data/nginx/break
[root@centos8 ~]# mkdir /data/nginx/test1
[root@centos8 ~]# mkdir /data/nginx/test2

[root@centos8 ~]# echo break > /data/nginx/break/index.html
[root@centos8 ~]# echo test1 > /data/nginx/test1/index.html
[root@centos8 ~]# echo test2 > /data/nginx/test2/index.html

#break访问测试:注意下面的index.html必须加
[root@centos7 ~]# curl -i www.longxuan.vip/break/index.html
...
test1

#最终的结果不会超出break的所在的location而且不会继续匹配当前location后续的write规则,而且直接返回数据给客户端。

break适用于不改变客户端访问方式,但是要将访问的目的URL做单次重写的场景,比如:有V1/V2两个版
本的网站前端页面并存,旧版本的网站数据在statics,当前还不能丢失,但是要将访问新版本的请求重写到新的静态资源路径static

location /staticsd { #旧路径重写至新路径,再响应
    root /data/nginx;
    index index.html;
    rewrite ^/staticsd/(.*) /static/$1 break;
}

location /static { #新路径也可以直接响应请的请求
    root /data/nginx;
    index index.html;
}

#旧路径第一次测试:
[root@localhost ~]# mkdir -p /data/nginx/staticsd
[root@localhost ~]# echo /data/nginx/staticsd/old > /data/nginx/staticsd/index.html
#访问
[root@localhost ~]# curl www.longxuan.vip/staticsd/
/data/nginx/staticsd/old

#跳转新路径第二次测试:
[root@localhost ~]# mkdir /data/nginx/static -p
[root@localhost ~]# echo /data/nginx/static/new > /data/nginx/static/index.html
#访问
[root@localhost ~]# curl www.longxuan.vip/staticsd/ -L
/data/nginx/static/new

last 案例

last:对某个location的URL匹配成功后,会停止当前location的后续rewrite规则,并结束当前location,
然后将匹配生成的新URL跳转至其他location继续匹配,直到没有location可匹配后, 将最后一次location
的数据返回给客户端。
last 适用于要不改变客户端访问方式但是需做多次目的URL重写的场景,使用场景不是很多。

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location /test2 {
    default_type text/plain;
    return 666 "new test2";
    #echo "new test2";
}

location /test1 {
    default_type text/plain;
    #return 996 "new test1";
    #echo "new test1";
    rewrite ^/test1/(.*) /test2/$1 last;
}

location /last {
    root /data/nginx;
    index index.html;
    rewrite ^/last/(.*) /test1/$1 last;
    rewrite ^/test1/(.*) /test2/$1 last;    #如果第一条rewrite规则匹配成功则不执行本条,否则执行本条rewrite规则。
}

#last访问测试:
[root@centos8 ~]# curl -L http://www.longxuan.vip/last/index.html
new test2    #会匹配多个location,直到最终全部匹配完成,返回最后一个location的匹配结果给客户端。

rewrite案例: 自动跳转 https

案例:基于通信安全考虑公司网站要求全站 https,因此要求将在不影响用户请求的情况下将http请求全
部自动跳转至 https,另外也可以实现部分 location 跳转

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    listen 443 ssl;
    listen 80;
    ssl_certificate /apps/nginx/certs/www.longxuan.vip.crt;
    ssl_certificate_key /apps/nginx/certs/www.longxuan.vip.key;
    ssl_session_cache shared:sslcache:20m;
    ssl_session_timeout 10m;
    server_name www.longxuan.vip;
    location / { #针对全站跳转
        root /data/nginx/html/pc;
        index index.html;
        if ($scheme = http ){ #如果没有加条件判断,会导致死循环
            rewrite / https://$host redirect;
        }
    }
    location /login { #针对特定的URL进行跳转https
        if ($scheme = http ){ #如果没有加条件判断,会导致死循环
            rewrite / https://$host/login redirect;
        }
    }
}

#重启Nginx并访问测试
[root@centos7 ~]# curl -ikL www.longxuan.vip
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0
Date: Thu, 08 Oct 2020 15:23:
...
Location: https://www.longxuan.vip
HTTP/1.1 200 OK
Server: nginx/1.18.0
pc web

范例: 如果是因为规则匹配问题导致的陷入死循环

[root@centos7 ~]# curl -IkL http://www.longxuan.vip
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0
Date: Thu, 08 Oct 2020 13:07:19 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://www.longxuan.vip/
HTTP/1.1 302 Moved Temporarily
Server: nginx/1.18.0
Date: Thu, 08 Oct 2020 13:07:19 GMT
Content-Type: text/html
Content-Length: 145
Connection: keep-alive
Location: https://www.longxuan.vip/
HTTP/1.1 302 Moved Temporarily
...
curl: (47) Maximum (50) redirects followed

rewrite 案例: 判断文件是否存在

案例:当用户访问到公司网站的时输入了一个错误的URL,可以将用户重定向至官网首页

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
location / {
    root /data/nginx/html/pc;
    index index.html;
    if (!-e $request_filename) {
        rewrite .* http://www.longxuan.vip/index.html; #实现客户端浏览器的302跳转
        #rewrite .* /index.html; #web服务器内部跳转
    }
}

#重启Nginx并访问测试
其它案例
#案例1:如果客户端浏览器包含MSIE,则rewrite客户端请求到/msie目录下
if ( $http_user_agent ~ MSIE){
rewrite ^(.*)$ /msie/$1 break;
}
#案例2: 更换目录访问方式,目录转换为对象存储形式
#要求:
#/20210606/static ->/static?id=20210606
#/20210123/image ->/image?id=20210123
rewrite ^/(\d+)/(.+)/ /$2?id=$l last;
#案例3:多目录转换访问方式
#要求: www.longxuan.com/images/20210106/1.jpg => www.longxuan.com/index.do?name=images&dir=20210106=&file=1.jpg
#规则配置:
if ($host ~* (.*)\.loongxuan\.com) {
   rewrite ^/(.*)/(\d+)/(.*)$ /index.do?name=$1&dir=$2&file=$3 last;
}

Nginx 防盗链

防盗链基于客户端携带的referer实现,referer是记录打开一个页面之前记录是从哪个页面跳转过来的标
记信息,如果别人只链接了自己网站图片或某个单独的资源,而不是打开了网站的整个页面,这就是盗
链,referer就是之前的那个网站域名,正常的referer信息有以下几种:

none:#请求报文首部没有referer首部,比如用户直接在浏览器输入域名访问web网站,就没有referer信息。
blocked:#请求报文有referer首部,但无有效值,比如为空。
server_names:#referer首部中包含本主机名及即nginx 监听的server_name。
arbitrary_string:#自定义指定字符串,但可使用*作通配符。示例: *.longxuan.vip www.longxuan.*
regular expression:#被指定的正则表达式模式匹配到的字符串,要使用~开头,例如:
~.*\.longxuan\.com

正常通过搜索引擎搜索web 网站并访问该网站的referer信息如下:

[root@centos8 ~]# tail -f /apps/nginx/logs/longxuan.org_access.log
172.31.0.1 - - [11/Oct/2021:09:28:10 +0800] "GET /images/logo.png HTTP/1.1" 302
145 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/86.0.4240.75 Safari/537.36 Edg/86.0.622.38" "-"
172.31.0.1 - - [11/Oct/2021:09:30:39 +0800] "GET /images/logo.png HTTP/1.1" 200
5934 "http://172.31.0.18/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
Edg/86.0.622.38" "-"
172.31.0.1 - - [11/Oct/2021:09:32:20 +0800] "GET /images/logo.png HTTP/1.1" 200
5934 "http://www.longxuan.vip/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
Edg/86.0.622.38" "-"
172.31.0.1 - - [11/Oct/2021:09:35:07 +0800] "GET /test1.html HTTP/1.1" 200 283 "-"
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)
Chrome/86.0.4240.75 Safari/537.36 Edg/86.0.622.38" "-"
172.31.0.1 - - [11/Oct/2021:09:35:48 +0800] "GET / HTTP/1.1" 200 7
"http://www.longxuan.vip/test1.html" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
Edg/86.0.622.38" "-"
172.31.0.1 - - [11/Oct/2021:09:37:39 +0800] "GET /images/logo.png HTTP/1.1" 200
5934 "http://www.baidu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" "-"
10.0.0.1 - - [11/Oct/2021:09:38:17 +0800] "GET /images/logo.png HTTP/1.1" 200
5934 "http://www.baidu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" "-"
172.31.0.1 - - [11/Oct/2021:09:41:35 +0800] "GET / HTTP/1.1" 304 0
"http://www.baidu.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36" "-"

json格式日志

#通过搜索引擎访问web网站的referer信息:
==> /apps/nginx/logs/access_json.log <==
{"@timestamp":"2011-06-
28T13:58:46+08:00","host":"172.31.0.100","clientip":"172.31.0.1","siz
e":0,"responsetime":0.000,"upstreamtime":"-","upstreamhost":"-
","http_host":"www.longxuan.vip","uri":"/index.html","domain":"www.longxuan.vip","xff":"-","referer":"https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=www.longxuan.vip&oq=www.longgxue.net&rsv_pq=d63060680002eb69&rsv_t=de01TWnmyTdcJqph7SfI1hXgXLJxSSfUPcQ3QkWdJk%2FLNrN95ih3XOhbR
s4&rqlang=cn&rsv_enter=1&inputT=321&rsv_sug3=41&rsv_sug2=0&rsv_sug4=1626","tcp_xff":"","http_user_agent":"Mozilla/5.0 (Windows NT 6.1; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119
Safari/537.36","status":"304"}

实现盗链

在一个web 站点盗链另一个站点的资源信息,比如:图片、视频等

#新建一个主机www.longgxue.top,盗取另一台主机www.longxuan.vip的图片
[root@centos8 conf.d]# pwd
/apps/nginx/conf/conf.d
[root@centos8 conf.d]# cat longgxue.top.conf
server {
    listen 80;
    server_name www.longgxue.top;
    location / {
        index index.html;
        root "/data/nginx/html/longxuan";
        access_log /apps/nginx/logs/longxuan.top_access.log main;
    }
}

#准备盗链web页面:
[root@centos8 conf.d]# mkdir /data/nginx/html/longg
[root@centos8 conf.d]# cat /data/nginx/html/longg/daolian.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>盗链</title>
</head>
<body>
<img src="http://www.longxuan.vip/images/logo.png" >
<h1 style="color:red">欢迎大家</h1>
<p><a href=http://www.longxuan.vip>永恒国度</a>欢迎你</p>
</body>
</html>

#重启Nginx并访问http://www.longgxue.top/daolian.html 测试
#验证两个域名的日志,是否会在被盗连的web站点的日志中出现以下盗链日志信息:
[root@centos8 ~]# tail /apps/nginx/logs/longxuan.vip_access.log
172.31.0.1 - - [13/Jun/2021:16:39:57 +0800] "GET /images/logo.png HTTP/1.1" 200 73737 "http://www.longgxue.top/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.101 Safari/537.36"

实现防盗链

基于访问安全考虑,nginx支持通过ngx_http_referer_module模块,检查访问请求的referer信息是否有效实现防盗链功能

官方文档:

https://nginx.org/en/docs/http/ngx_http_referer_module.html

语法格式:

location /images {
    root /data/nginx/html/pc;
    index index.html;
    valid_referers none blocked server_names
          *.example.com example.* www.example.org/galleries/ ~\.google\.;
    if ($invalid_referer) {
       return 403;
    }
}

范例: 定义防盗链:

[root@centos8 ~]# vim /apps/nginx/conf/conf.d/pc.conf
server {
    index index.html;
    valid_referers none blocked server_names *.longxuan.vip *.longxuan.top ~\.google\. ~\.baidu\. ~\.bing\. ~\.so\. ~\.dogedoge\. ; #定义有效的referer
    if ($invalid_referer) { #假如是使用其他的无效的referer访问
        return 403 "Forbidden Access"; #返回状态码403
    }
......
}

#重启Nginx并访问测试
#指定referer为http://www.baidu.com进行访问
[root@centos7 ~]# curl -e 'http://www.baidu.com' www.longxuan.vip/images/logo.png

#指定referer为http://www.xxx.com进行访问,被拒绝
[root@centos7 ~]# curl -e 'http://www.xxx.com' www.longxuan.vip/images/logo.png

#不加http的referer不会拒绝
[root@centos7 ~]# curl -e 'www.xxx.com' www.longxuan.vip/images/logo.png

在被盗链的nginx服务器查看日志

[root@localhost ~]# tail -f /apps/nginx/logs/longxuan.vip_access.log 
172.31.0.1 - - [13/Jun/2021:17:02:19 +0800] "GET /images/logo.png HTTP/1.1" 403 16 "http://www.longgxue.top/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"
172.31.0.1 - - [13/Jun/2021:17:02:21 +0800] "GET /images/logo.png HTTP/1.1" 403 16 "http://www.longgxue.top/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0"

172.31.0.17 - - [13/Jun/2021:17:06:47 +0800] "GET / HTTP/1.1" 403 153 "http://www.baidu.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:07:02 +0800] "GET / HTTP/1.1" 403 153 "http://www.xxx.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:07:09 +0800] "GET / HTTP/1.1" 403 153 "www.xxx.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:14:29 +0800] "GET /images/logo.html HTTP/1.1" 404 153 "www.xxx.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:14:37 +0800] "GET /images/logo.png HTTP/1.1" 200 73737 "www.xxx.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:14:53 +0800] "GET /images/logo.png HTTP/1.1" 403 16 "http://www.xxx.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:15:08 +0800] "GET /images/logo.png HTTP/1.1" 200 73737 "http://www.baidu.com" "curl/7.29.0"
172.31.0.17 - - [13/Jun/2021:17:15:33 +0800] "GET /images/logo.png HTTP/1.1" 200 73737 "http://www.google.com" "curl/7.29.0"

其它相关高级功能

第三方模块

https://github.com/agile6v/awesome-nginx/

Lua 参考网站

https://www.runoob.com/lua/lua-tutorial.html

自动生成 nginx 配置文件

#需要科学上网
https://www.digitalocean.com/community/tools/nginx
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值