Mod rewrite 如何进行干净的Mod_重写,隐藏在查询字符串中传递的变量号,但只显示php中的标题?
我开发web应用程序已经有一段时间了。由于我的网站生成的动态链接,我的应用程序在搜索引擎结果中表现不佳 我很欣赏一些开发人员重写mod_以生成以下内容的方式: 运行“index.php?category_id=2&country=23”的替代品Mod rewrite 如何进行干净的Mod_重写,隐藏在查询字符串中传递的变量号,但只显示php中的标题?,mod-rewrite,Mod Rewrite,我开发web应用程序已经有一段时间了。由于我的网站生成的动态链接,我的应用程序在搜索引擎结果中表现不佳 我很欣赏一些开发人员重写mod_以生成以下内容的方式: 运行“index.php?category_id=2&country=23”的替代品 如何在我的URL中实现这一点?您需要一个映射来将名称映射到ID。您可以使用mod_rewrite执行此操作。或者,我建议您可以使用PHP来实现: // maps that map the names to IDs $categories = array(
如何在我的URL中实现这一点?您需要一个映射来将名称映射到ID。您可以使用mod_rewrite执行此操作。或者,我建议您可以使用PHP来实现:
// maps that map the names to IDs
$categories = array('accommodation'=>2 /*, … */);
$countries = array('europe'=>23 /*, … */);
$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', trim($_SERVER['REQUEST_URI_PATH'], '/'));
// map category name to ID
$category = null;
if (isset($segments[0])) {
if (isset($categories[$segments[0]])) {
$category = $categories[array_shift($segments)];
} else {
// category not found
}
} else {
// category missing
}
// map country name to ID
$country = null;
if (isset($segments[0])) {
if (isset($countries[$segments[0]])) {
$country = $countries[array_shift($segments)];
} else {
// country not found
}
} else {
// country missing
}
现在,您只需要一条规则就可以将请求重写为PHP脚本:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule %{REQUEST_FILENAME} !-d
RewriteRule !^index\.php$ index.php [L]
此规则不包括URL可以映射到现有常规文件(-f
)或现有目录(-d
)的请求
编辑因为你真的想反过来:如果你仍然想用PHP解决这个问题,那么你只需要反向映射(只需交换键和值)和重定向的
头
函数:
// maps that map the IDs to names
$categories = array(2=>'accommodation' /*, … */);
$countries = array(23=>'europe' /*, … */);
$newPath = '';
// map category ID to name
if (isset($_GET['category_id'])) {
if (isset($categories[$_GET['category_id']])) {
$newPath .= '/'.$categories[$_GET['category_id']];
} else {
// category not found
}
} else {
// category missing
}
// map country ID to name
if (isset($_GET['country'])) {
if (isset($countries[$_GET['country']])) {
$newPath .= '/'.$countries[$_GET['country']];
} else {
// country not found
}
} else {
// country missing
}
header('Location: http://example.com'.$newPath);
exit;
您应该添加一些错误处理,因为当前重定向即使在两个参数都丢失的情况下也会发生。Hi Gumbo,谢谢您的回答,我想重写的是:“index.php?category_id=2&country=23”类别和国家的url存储在数据库中。@Jay Bee:那么你真的希望
/index.php?category_id=2&country=23
的请求被重定向到/accountment/europe
?@Gumbo,是的,这就是我要找的。