Url 重写,htaccess 和 PHP 怎么做

Url rewrite, htaccess and PHP how to do it

我对此 url 有疑问,我想知道如何将其重写到 htaccess 中。我对这些东西很陌生,所以我很好奇如何做到这一点,例如这个 url: 网站/?page=在线

并将其重写为,例如: WEBSITE/page/online

或这个url: 网站/?page=account&hide=x

例如: WEBSITE/page/account/hide/x

我使用此 PHP 脚本将页面包含在一个 HTML 文档中:

    <?php

    if (empty($_GET)) 
    {
        include 'pages/index.php';
    } else {
        if (!file_exists('pages/' . $_GET['page'] . '.php' ))
        {
            header("Location: /");
        } else {
            include 'pages/' . $_GET['page'] . '.php';
        }
    }

?>

你可以这样做。

.htaccess 文件

RewriteEngine On
RewriteRule (.*) control.php [L]

这表示接收每个到达您服务器的请求并将其发送到 control.php 文件中。然后在 control.php 中,我们处理对目录的所有获取。您可能需要一些后备方案,例如没有 GET 请求;它应该转到根目录、404、403 吗?

control.php

<?php
$parts = '';
foreach($_GET as $key => $directories) {
    $parts .= $key . '/' . $directories . '/';
}
header('Location: ' . '/' . $parts);
?>

在您的 .htaccess 文件中

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Match SITE/page/account/hide/x, etc
RewriteRule ^/?page/([^\.*]+)/([^\.*]+)/([^\.*]+)?$ index.php?page=&= [L,QSA]

# Match /SITE/page/online etc.
RewriteRule ^/?page/([^\.*]+)/?$ index.php?page= [L,QSA]