我们都知道wordpress有下面这样简单的。htaccess代码RewriteEngine上RewriteBase/
# only rewrite if the requested file doesn't exist
RewriteCond %{REQUEST_FILENAME} !-s
# pass the rest of the request into index.php to handle
RewriteRule ^(.*)$ /index.php/$1 [L]
但是如果我将所有请求重定向到index.php,我认为在php中处理每次重写会变得非常麻烦。目前我有一个逻辑在脑海中,像维护一个db表与所有有效的重定向。但我仍然不知道如何处理([0-9]+)这样的规则。
如果有人以前实现过这样的东西,或者有一个逻辑,你能在这件事上指导我吗
我这样做的唯一目的,是因为我想在我的网站的菜单中添加/删除类别的灵活性。我不想每次都去。htaccess,然后到处编辑。我想创建一个更像CMS用户可以添加删除类别
我的建议是设置基于php的路由,基本思路是这样做:
RewriteEngine On
# skip all files with extensions other than .html
# this way if you want you can append the .html to dynamic pages
# which wont really exist as a file
RewriteCond %{REQUEST_URI} '..+$
RewriteCond %{REQUEST_URI} !'.html$
RewriteRule .* - [L]
// redirect everything to your front controller
RewriteRule ^(.*)$ index.php [QSA,L]
注意你是如何把所有的东西都放到index.php
的,但你没有重写任何变量或任何东西。这是因为您将使用php根据URL的模式确定要做什么。为了做到这一点,你需要实现一个路由器。基本上,路由器接受请求并将其与模式进行匹配,然后根据模式确定任何参数。
有现成的库可以为你做这些。例如Zend_Controller_Router
。
我不明白这个问题,WordPress已经为你处理了所有这些。除非你的意思是你不使用WordPress?在这种情况下,两种方法都可以。你想要什么样的URL结构?你可以这样写规则:
RewriteRule ^category/(.*)$ categories.php?cat=$1 [L]
将类似domain.com/category/dogs的URL重写为domain.com/categories.php?cat=dogs。显然,你可以根据自己的喜好进行调整,并为标签、帖子等编写更多类似的规则。
在php中处理路由将是一个更动态和"优雅"的解决方案。你可以尝试使用CodeIgniter这样的框架,它会自动为你管理路由,让你更容易定义自定义路由。可能比写一堆。htaccess规则要好。