2011-03-23 100 views
2

我尝试使用下面的代码重写动态URL动态网址:问题重写使用mod_rewrite

RewriteRule (.*)/$ index.php?location=$1 
RewriteRule (.*)/(.*)/$ index.php?location=$1&company=$2 

我真的很需要两个重写,你可以从上面的代码中看到。首先,如果全部存在,我需要页面重写位置。例如,它会将site.ccom/index.php?location = sandiego变成site.com/sandiego/
这是正常工作。

但是,当我尝试添加第二个变量时失败。它设法检测& company = 1变量,但由于某种原因它将?location = sandiego变量作为'index.php'返回。例如,如果我输入以下内容:site.com/san-diego/1/,然后尝试获取$ location和$ company变量,它将只会成功获取$ company变量,并且$ location变量将被设置到'index.php',而不是'san-diego'。

任何帮助将不胜感激。

回答

1

我想我找到了解决方案。我使用了以下内容:

RewriteRule ^([a-z0-9-]+)/?$ index.php?location=$1 [NC] 
RewriteRule ^([a-z0-9-]+)/([a-z0-9-]+)/?$ index.php?location=$1&company=$2 [NC] 

这似乎是完美的工作,并成功重定向都site.com/sandiego/和site.com/sandiego/1/

0

尝试那些:

RewriteRule ^([a-z0-9]+)/?$ index.php?location=$1 [NC] 
RewriteRule ^([a-z0-9]+)/([a-z0-9]+)/?.*$ index.php?location=$1&company=$2 [NC] 

请记住,试图捕捉任何字符序列(例如通过使用(.*)(.+))做URL重写时,通常是一个坏主意,因为在此线程解释:http://www.sitepoint.com/forums/apache-configuration-199/rewrite-eliminate-trailing-slash-arbitrary-parameters-520302.html#post3657601

+0

对不起,没有那些工作在所有。他们都返回了404错误。 – Jeremy 2011-03-23 21:57:51

+0

对不起,我已将'index.php'重命名为'rewrite.php'进行测试,并忘记将其改回... =>编辑我的答案。 – 2011-03-23 22:08:06

+0

是的,一个想法,并重新命名为index.php。但它仍然不起作用。回到我原来的代码,我可以得到任何一个或另一个工作。如果我只是使用这一行:'RewriteRule(。*)/ $ index.php?location = $ 1',它会完全重定向site.com/sandiego/。如果我只使用这一行:'RewriteRule(。*)/(。*)/ $ index.php?location = $ 1&company = $ 2',它将完全重定向到site.com/sandiego/1/。但是,当我一起使用它们时,它们全部崩溃。 – Jeremy 2011-03-23 22:09:58

0
Try ([^\/]*)/([^\/]*)/$ instead of (.*)/(.*)/$
+0

感谢您的回复,但我认为我解决了这个问题(下面发布)。如果我的解决方案无效,我会尽快回复您,并会测试您的方法。再次感谢。 – Jeremy 2011-03-23 23:06:47