Nginx if语句加正则表达式实现字符串截断
时间:2015-02-19 13:52 来源:linux.it.net.cn 作者:IT
在给大家讲述这个问题之前,先给大家看一段nginx配置. 我们用到了 set-misc-nginx-module
location /test/ {
default_type text/html;
set_md5 $hash "secret"$remote_addr;
echo $hash;
}
这样输出来的内容,可能是下面这样的
202cb962ac59075b964b07152d234b70
但如果我们要截取某几位字符怎么办呢?
首先大家想到的肯定是使用模块来实现, 但只能这样吗? 有没有更方便的方式呢?
有的.
我们可以巧妙地使用if + 正则表达式来实现这个小需求:
location /test/ {
default_type text/html;
set_md5 $hash "secret"$remote_addr;
if ( $hash ~ ^[\w][\w][\w][\w][\w][\w][\w][\w]([\w][\w][\w][\w][\w][\w][\w][\w]) ) {
set $hash $1;
}
echo $hash;
}
访问/test/输出的就是:
ac59075b
(责任编辑:IT)
在给大家讲述这个问题之前,先给大家看一段nginx配置. 我们用到了 set-misc-nginx-module location /test/ { default_type text/html; set_md5 $hash "secret"$remote_addr; echo $hash; } 这样输出来的内容,可能是下面这样的 202cb962ac59075b964b07152d234b70 但如果我们要截取某几位字符怎么办呢? 首先大家想到的肯定是使用模块来实现, 但只能这样吗? 有没有更方便的方式呢?
有的. location /test/ { default_type text/html; set_md5 $hash "secret"$remote_addr; if ( $hash ~ ^[\w][\w][\w][\w][\w][\w][\w][\w]([\w][\w][\w][\w][\w][\w][\w][\w]) ) { set $hash $1; } echo $hash; } 访问/test/输出的就是:
ac59075b
(责任编辑:IT) |