繁体   English   中英

需要帮助复制 .htaccess mod_rewrite 重定向 function 在 php 像 ZDCEC9B13C12DE51501ZA3BC0

[英]Need help to replicate .htaccess mod_rewrite redirection function in php like Wordpress

我们都知道 wordpress 有简单的 .htaccess 代码如下 RewriteEngine on 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 中的每次重写都会变得非常麻烦。 目前我有一个逻辑,比如维护一个包含所有有效重定向的数据库表。 但我仍然不知道如何处理规则喜欢 ([0-9]+)。

如果有人以前实施过这样的事情或有逻辑,请你指导我这件事

这样做的唯一目的是因为我希望灵活地在我的网站菜单中添加/删除类别。 我不想每次都从 go 到 .htaccess 并在所有地方进行编辑。 我想创建更像一个 CMS,用户可以在其中添加删除类别

我不明白这个问题,WordPress 已经为你处理了这一切。 除非你的意思是你没有使用 WordPress? 在这种情况下是的,你可以这样做。 你想要什么样的URL结构? 你可以像这样写一个规则:

RewriteRule ^category/(.*)$  categories.php?cat=$1 [L]

要使 URL 像 domain.com/category/dogs 重写到 domain.com/categories.php?cat=dogs。 显然你可以根据自己的喜好调整它,并为标签、帖子等编写更多类似的规则。

在 php 中处理路由将是一个更加动态和“优雅”的解决方案。 您可以尝试使用 CodeIgniter 之类的框架,这将自动为您管理路由并轻松定义自定义路由。 可能比写一堆 .htaccess 规则要好。

我的建议是设置基于 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]

请注意,您如何将所有 go 设置为index.php ,但您不会重写任何变量或任何东西。 这是因为您将根据 URL 和 php 的模式计算出要做什么。 为此,您需要实现一个路由器。 基本上,路由器接受请求并将其与模式匹配,然后根据模式确定任何参数。

现有的库可以为您执行此操作。 例如Zend_Controller_Router

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM