.htaccess - 重复页面。阻止没有变量PHP的地址
问题描述
我想达到这个效果:
https://example.home/blog.php --- 重定向 --> 404,
https://example.home/blog.php?id= ... --- 重定向 --> blog.php?id= (这里是随机 ID,从 1 到 1000 - 例如)
网站显示在:/blog.php?id=57,
而且在这个地址:/blog.php?id=test-post
您如何阻止索引包含 ID 的网址?
如何让网站地址看起来像这样:http://example.home/blog/test-post
解决方案
这里有一个 mod_rewrite 的完整指南,看起来很不错。您必须向下滚动一点才能将 url 作为参数。
https://www.brand3.com/blog/htaccess-mod_rewrite-ultimate-guide/
如果您不想过多地使用 mod_rewrite 并且已经通过单个公共 index.php 指导所有内容(无论如何这是一个好主意)。然后你可以做一些像这样更脏的事情。
/**
* Get the given variable from $_REQUEST or from the url
* @param string $variableName
* @param mixed $default
* @return mixed|null
*/
function getParam($variableName, $default = null) {
// Was the variable actually part of the request
if(array_key_exists($variableName, $_REQUEST))
return $_REQUEST[$variableName];
// Was the variable part of the url
$urlParts = explode('/', preg_replace('/\?.+/', '', $_SERVER['REQUEST_URI']));
$position = array_search($variableName, $urlParts);
if($position !== false && array_key_exists($position+1, $urlParts))
return $urlParts[$position+1];
return $default;
}
请注意,这将首先检查任何具有相同名称的 _GET、_POST 或 _HEADER 参数。然后它检查给定键的 url 的每个部分,并返回以下部分。因此,您可以执行以下操作:
// On http://example.com/news/18964
getParam('news');
// returns 18964
推荐阅读
- r - 带有图像的多个 Kable 表
- python - 在 SuperLearner 集成模型中使用神经网络作为基础学习器
- c++ - 通过智能指针和转换对基础模板参数进行模板推导
- python - 如何使用 pytest 测试类方法
- wine - 如何修复 Wine 内存访问冲突
- angular - 将项目彼此下方放置在一个锚项目中
- excel - 结合 .csv 并将文件名添加为列
- css - How to use next-css in next.config.js in combination with custom server Express
- c# - 我可以使用内存中实体框架 6.2.0 还是有任何方法可以做到这一点
- java - 如何防止 Spring 创建一个只是要扩展的“抽象”泛型类型存储库?