首页 > 解决方案 > 重复页面。阻止没有变量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

标签: .htaccess

解决方案


这里有一个 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

推荐阅读