【问题标题】:Joomla-like url rewrite类似 Joomla 的 url 重写
【发布时间】:2015-07-31 17:11:43
【问题描述】:

我知道已经有人问过类似的问题,但我找不到任何关于我的特定“问题”的信息。 我想做的是以一种非常动态的方式进行以下操作,这意味着“超级用户”应该能够在管理界面中定义新路由:

如果用户输入http://www.example.com/nice-url/

他应该被重定向到http://www.example.com/category.php?id=123而不更改网址。

现在有几种方法可以实现这一目标。要么我像这样使用 .htaccess:

RewriteEngine on
RewriteRule ^nice-url category.php?id=123 [L]

这可行,但不是很动态。我需要让一个 php 脚本在底部附加新规则,这不是我想做的事情。

或者这个:

.htaccess

 FallbackResource /process.php

process.php

$path = ltrim($_SERVER['REQUEST_URI'], '/');  
$elements = explode('/', $path);               

if(count($elements) == 0) {                  
    header("Location: http://www.example.com");
    exit;
}

$sql = sprintf("SELECT Target FROM urlrewrites WHERE Source = '%s' LIMIT 1", array_shift($elements));
$result = execQuery($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$target = $row['Target'];

header("Location: ".$target);
exit;

这也有效,但遗憾的是地址栏中的 url 被更改了。两者之间有办法吗?拥有 PHP 的灵活性和RewriteEngine 的“沉默”?像 joomla 这样的优秀 CMS 是如何做到的?他们是否为您创建的每个新页面生成一个 htaccess 文件? 谢谢!

【问题讨论】:

    标签: php apache .htaccess mod-rewrite joomla


    【解决方案1】:

    如果你使用正则表达式会更加动态。这就是它在 Joomla 等 CMS 系统中的工作方式。好主意是安装带有“nice” URL 的 Joomla 并查看 .htacces 文件以了解它是如何工作的。 你可以从这里开始: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/

    【讨论】:

    • 我知道正则表达式。我的主要问题是:他们如何处理用户添加的其他页面?我不相信他们会在添加新页面时重写整个 .htaccess 文件。问题也是我事先不知道具体路线。
    • 在 Joomla 中,它是使用路由机制实现的,其概念在此处描述:docs.joomla.org/Supporting_SEF_URLs_in_your_component,总体思路在这里:docs.joomla.org/Routing_implementation_details
    • 看起来没有人能清楚地解释如何用纯 PHP 实现它。谁有例子?
    【解决方案2】:

    你可以在 root .htaccess 中拥有这段代码:

    RewriteEngine on
    
    # If the request is not for a valid directory
    RewriteCond %{REQUEST_FILENAME} !-d
    # If the request is not for a valid file
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ category.php?uri=$1 [L,QSA]
    

    PS:请注意,这会将/nice-url 路由到/category.php?uri=nice-url。然后在category.php 中,您可以进入您的数据库并将$_GET['uri'] 转换为id

    【讨论】:

      猜你喜欢
      • 2013-09-28
      • 2013-03-09
      • 2014-05-14
      • 1970-01-01
      • 2010-12-02
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多