2015-05-19 60 views
1

我知道类似的问题已经被问到,但我找不到任何有关我的具体“问题”的信息。 我想要做的是在一个非常动态的方式,这意味着“超级用户”应该能够在一个管理界面来定义新的路线如下:如果用户输入http://www.example.com/nice-url/Joomla-like url rewrite

他应该得到

重定向到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的“沉默”?伟大的CMS如joomla如何做到这一点?他们是否为您创建的每个新页面生成一个htaccess文件? 谢谢!

回答

0

你可以有这样的代码在根目录的.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

0

如果您使用正则表达式,它会更具动态性。这就是它在Joomla等CMS系统中的工作原理。好主意是在Joomla上安装'nice'网址并查看.htacces文件以了解它是如何工作的。 你可以从这里开始: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/

+0

那么我知道正则表达式。我的主要问题是:他们如何处理额外的页面,由用户添加?我不相信他们在添加新页面时重写整个.htaccess文件。问题还在于我不知道具体的路线。 – puelo

+0

在Joomla中,它使用路由机制来实现,其概念在此处描述:https://docs.joomla.org/Supporting_SEF_URLs_in_your_component ,总体思路如下: https://docs.joomla.org/Routing_implementation_details –