URL重写正则表达式与可选捕获

时间:2014-07-23 22:13:08

标签: regex .htaccess

我有这些类型的网址:

/manage/123
/manage_foo/456
/manage_bar/789

/manage
/manage_foo
/manage_bar

我需要改写为:

/manage.php?id=123
/manage_foo.php?id=456
/manage_bar.php?id=789

/manage.php?id=
/manage_foo.php?id=
/manage_bar.php?id=

如何捕获id可选项?我知道如果id存在,这是有效的:

RewriteCond %{REQUEST_URI} ^\/(manage.*)\/(.*)$
RewriteRule ^ %1.php?id=%2 [NC,L]

如果在id

之前删除斜杠,那么正则表达式会崩溃

1 个答案:

答案 0 :(得分:0)

您可以使用此规则:

Options -MultiViews
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(manage)(?:/([0-9]*))?/?$ $1.php?id=$2 [QSA,L,NC]