.htaccess重写干净的URL w / 2获取变量

时间:2011-02-10 15:32:21

标签: .htaccess

我现在的.htacess看起来像这样:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9-z\-]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9-z\-]+)/$ index.php?page=$1

允许我使用

等链接
http://www/myserver.com/somepage 

并将其重写为

http://www.myserver.com/?page=somepage.

但是如何让它更深入?我希望能够做到:

http://www.myserver.com/somepage/subpage

并将其转换为

http://www.myserver.com/?page=somepage&subpage=subpage

由于

3 个答案:

答案 0 :(得分:2)

使用第二个参数的附加捕获组添加以下规则

RewriteRule ^([a-zA-Z0-9-z\-]+)/([a-zA-Z0-9-z\-]+)$ index.php?page=$1&subpage=$2
RewriteRule ^([a-zA-Z0-9-z\-]+)/([a-zA-Z0-9-z\-]+)/$ index.php?page=$1&subpage=$2

答案 1 :(得分:0)

如果您有可能捕获没有子页面的链接,那么您需要使用第一个规则捕获子页面。然后你可以抓住其余的并发送到页面。

RewriteEngine On
# catch potential subpages first
RewriteRule ^([a-zA-Z0-9-z\-]+)/([a-zA-Z0-9-z\-]+)/?$ index.php?page=$1&subpage=$2 [L]
#combines your original rule to allow for optional end slash
RewriteRule ^([a-zA-Z0-9-z\-]+)/?$ index.php?page=$1 [L]

您可以将它们合并为一个规则,但它可能会生成带有空子页面的查询。我更喜欢更清晰的内部查询,但为了论证:

RewriteEngine On
# One rule to rule them all
RewriteRule ^([a-zA-Z0-9-z\-]+)(/([a-zA-Z0-9-z\-]+))?/?$ index.php?page=$1&subpage=$3 [L]

编辑:将此链接投掷到rewrite tester。很有用。虽然,当我测试我的规则时,它会带来原始[]分组的问题。最后的-z-是什么?

答案 2 :(得分:0)

RewriteEngine On
RewriteRule ^([a-zA-Z0-9-z\-\_]+)$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/$ index.php?page=$1
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)$ index.php?page=$1&id=$2
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)/$ index.php?page=$1&id=$2
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)$ index.php?page=$1&id=$2&value=$3
RewriteRule ^([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)/([a-zA-Z0-9-z\-\_]+)/$ index.php?page=$1&id=$2&value=$3