nginx 指令提取url的参数url的uri

以上两个url的参数redirect都是另一个url,想提取redirect的uri,例如/a/b?cd=将军令,该如何做呢?

以下测试配置可以做到,其中set_unescape_uri的作用是将转码过的url解码,属于set-misc-nginx-module;echo是测试打印用的,属于echo-nginx-module

关键点在于if ( $obj_uri ~ ^(http?://)([^:^/])(:\d)?(.*)? ) 用正则对字符串做切割,分成4段,当4个参数传入if作用域。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
worker_processes 1;
error_log /usr/local/var/log/nginx/error.log;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
access_log /usr/local/var/log/nginx/access.log main;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
echo "hello, world!";
}
location /test {
set $obj_uri $arg_uri;
set_unescape_uri $obj_uri;
if ( $obj_uri ~ ^(http?://)([^:^/]*)(:\\d*)?(.*)? ){
set $obj_uri $4;
echo $obj_uri;
}
if ( $obj_uri ~ ^(https?://)([^:^/]*)(:\\d*)?(.*)? ){
set $obj_uri $4;
echo $obj_uri;
}
echo $obj_uri;
}
}
include servers/*;
}

效果

1
2
/a/b?cd=将军令
/a/b/c?d=丑小鸭