类 Joomla url 重写
Joomla-like url rewrite
我知道已经有人问过类似的问题,但我找不到关于我的具体问题的任何信息 "problem"。
我想做的是以非常动态的方式进行以下操作,这意味着 "SuperUser" 应该能够在管理界面中定义新路由:
如果用户输入 http://www.example.com/nice-url/
他应该在不更改 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
的"silentness"?像 joomla 这样的优秀 CMS 是如何做到的?他们是否为您创建的每个新页面生成一个 htaccess 文件?
谢谢!
如果使用正则表达式会更动态。这就是它在 Joomla 等 CMS 系统中的工作方式。好主意是安装带有 'nice' URL 的 Joomla 并查看 .htacces 文件以了解它是如何工作的。
你可以从这里开始:
http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
您可以在 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= [L,QSA]
PS:注意这会将 /nice-url
路由到 /category.php?uri=nice-url
。然后在 category.php
中你可以进入你的数据库并将 $_GET['uri']
翻译成 id
.
我知道已经有人问过类似的问题,但我找不到关于我的具体问题的任何信息 "problem"。 我想做的是以非常动态的方式进行以下操作,这意味着 "SuperUser" 应该能够在管理界面中定义新路由:
如果用户输入 http://www.example.com/nice-url/
他应该在不更改 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
的"silentness"?像 joomla 这样的优秀 CMS 是如何做到的?他们是否为您创建的每个新页面生成一个 htaccess 文件?
谢谢!
如果使用正则表达式会更动态。这就是它在 Joomla 等 CMS 系统中的工作方式。好主意是安装带有 'nice' URL 的 Joomla 并查看 .htacces 文件以了解它是如何工作的。 你可以从这里开始: http://www.elated.com/articles/mod-rewrite-tutorial-for-absolute-beginners/
您可以在 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= [L,QSA]
PS:注意这会将 /nice-url
路由到 /category.php?uri=nice-url
。然后在 category.php
中你可以进入你的数据库并将 $_GET['uri']
翻译成 id
.