htacess-在url中使用可选值

时间:2019-02-07 10:57:06

标签: .htaccess

我的网址类似:

www.example.com => rewritten to www.example.com?type=default
www.example.com/foo => rewritten to www.example.com?page=foo&type=default
www.example.com/bar => rewritten to www.example.com?page=bar&type=default

并且我希望用户也能够使用

www.example.com/d/ => rewritten to www.example.com?type=d
www.example.com/e/ => rewritten to www.example.com?type=e
www.example.com/d/foo => rewritten to www.example.com?page=foo&type=d
www.example.com/e/foo => rewritten to www.example.com?page=foo&type=e
www.example.com/d/bar => rewritten to www.example.com?page=bar&type=d
www.example.com/e/bar => rewritten to www.example.com?page=bar&type=e

当前,我第一次使用简单的RewriteRule

RewriteRule ^(foo|bar)$ index.php?page=$1&type=default [QSA,L]

但是如何添加对特定类型的支持? 我可以做

RewriteRule ^(d|e)/(foo|bar)$ index.php?page=$2&type=$1[QSA,L]

但是有一种方法可以用一条规则编写它吗?

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式。

  

”?将匹配设置为可选。

RewriteRule ^(d|e)/?(foo|bar)?$ index.php?page=$2&type=$1 [QSA,L]

参考:https://httpd.apache.org/docs/2.4/rewrite/intro.html#regex