正则表达式:获取一个可选参数,可能很简单

时间:2016-02-12 17:28:47

标签: php html regex redirect nginx

我想知道是否有可能从正则表达式中获取可选参数。这是我试过的正则表达式:

rewrite ^/(m/)?string$ /page.php?p=$1

参数'm /'是可选的,但我想如果这个参数存在,那么p =“m”而不是字符串“m /".

换句话说:

/m/string  =>  /page.php?p=m
/string    =>  /page.php

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果你不能通过一个正则表达式解决问题..使用两个正则表达式!

rewrite ^/m/string$ /page.php?p=$1 last;
rewrite ^/string$ /page.php last;

last会停止原始网址的进一步匹配。