htaccess规范网址

时间:2016-04-09 01:56:23

标签: php regex apache .htaccess mod-rewrite

我对mod_rewrite的规范网址有点麻烦。这是我目前的htaccess:

RewriteEngine On
RewriteBase /reads

RewriteRule ^search/([^/]*)/?$ search.php?q=$1 [L]
RewriteRule ^([^/]*)/([^/]*)/?$ view.php?title=$1&chapter=$2 [L]

我正在尝试重写这些网址: website.com/reads/how-to-cook/9website.com/reads/view.php?title=how-to-cook&chapter=9

在我的PHP函数中,调用view.php?title=xyz将列出该标题中的所有章节,添加&chapter=xx将加载与所选标题对应的章节。

在这些情况下,脚本运行正常:

website.com/reads/how-to-cook/9
website.com/reads/economy-blah/5/
website.com/reads/good-recipes/

但是这个给出了404错误(省略了标题后面的斜杠),请告诉我如何修复错误,解释错误可能来自哪里会非常感激:

website.com/reads/good-recipes

第二个问题(如果在这里过于贪心,请原谅我)。我该怎么转:

website.com/reads/how-to-cook/9
website.com/reads/economy-blah/5/

website.com/reads/how-to-cook/chapter-9
website.com/reads/economy-blah/chapter-5/

使用mod_rewrite。 谢谢!

1 个答案:

答案 0 :(得分:0)

添加这2行

RewriteRule ^([^/]*)/([0-9]+)/?$ http://website.com/reads/$1/chapter-$2 [L,R=301]
RewriteRule ^([^/]*)?$ view.php?title=$1 [NC,L]

第一行更改了回答第二个问题的网址。从本质上讲,它将用户重定向到新的URL,仅在第二个参数为数字时才起作用。第二行定义规则中缺少的新条件。然后,完整的重写规则集将如下所示

RewriteEngine On
RewriteBase /reads

RewriteRule ^([^/]*)/([0-9]+)/?$ http://website.com/reads/$1/chapter-$2 [L,R=301]

RewriteRule ^search/([^/]*)/?$ search.php?q=$1 [L]
RewriteRule ^([^/]*)?$ view.php?title=$1 [NC,L]
RewriteRule ^([^/]*)/([^/]*)/?$ view.php?title=$1&chapter=$2 [L]