如何从 URL 中删除空的“?page=”参数以不显示它

How can I remove empty "?page=" parameter from URL to don't show it

大家好我有我的 URL http://localhost/?page= 当我有了它时我只想要 http://localhost/ 因为它正在加载相同的主页 URL 但我不想在 URL 中显示此“/?page=”。我怎样才能做到这一点?因为我试图在我的 PHP 文件夹结构

中创建一些 MVC
public function __invoke(){
    $page = (isset($_GET['page']) && !empty($_GET['page'])) ? $_GET['page'] : "home";

    switch ($page) {
        case "home":
            $title = "Home of APP";

            require __DIR__."/../views/includes/main-header.php"; 
                require __DIR__."/../views/home.php"; 
            require __DIR__."/../views/includes/main-footer.php";
        break;

        case "insertCategories":
            $this->category_sub_category_questions->insertCategories("Sitewide Creative");
            $this->category_sub_category_questions->insertCategories("Global Elements");
            $this->category_sub_category_questions->insertCategories("Core Ecommerce Pages");
            $this->category_sub_category_questions->insertCategories("Advanced Ecommerce Features");
            $this->category_sub_category_questions->insertCategories("Brand Pages");
            $this->category_sub_category_questions->insertCategories("Development Environment Setup");
            $this->category_sub_category_questions->insertCategories("Launch and Post-launch");
            $this->category_sub_category_questions->insertCategories("Measurement and Conversion Optimization");
            $this->category_sub_category_questions->insertCategories("Consulting Services");

            echo "Categories Inserted!";
        break;

        default:
            require __DIR__."/../views/errors/404.php"; 
        break;
    }
}

你可以试试这样的

$url = 'http://localhost/?page=';
echo $this->cleanUrl($url);

/**
 * Clear URL remove empty query strings from it.
 * @Input URL
 * @Return Cleaned URL without empty query strings

*/
public function cleanUrl($url){
    $params = parse_url($url);
    parse_str($params['query'], $query);
    // Remove empty
    $cleanedParams = array_filter($query);
    
    $url = strtok($url, '?');
    $url = rtrim($url, '/');
    if(!empty($cleanedParams)){
        $url = $url.'?'.http_build_query($cleanedParams);
    }
    return $url; 
}

我用这段代码找到了 .htaccess 的解决方案

RewriteCond %{QUERY_STRING} ^page=[^&]+&?(.*) [NC]
RewriteRule ^ %{REQUEST_URI}?%1 [R=302,L]