URL PHP 中的基本路由无法使用 .htaccess

Basic URL Routing in PHP Not working using .htaccess

我正在 Php 中构建一个基本的 URL 路由,我阅读了很多关于它的文章,但是当我尝试做同样的事情时,写的方式并没有发生。这是我的代码

.htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

index.php 页面

<?php

$request = $_SERVER['REQUEST_URI'];
echo $request;
switch ($request) {
    case '/' :
        require __DIR__ . '/views/home.php';
        break;
    case '' :
        require __DIR__ . '/views/home.php';
        break;
    case '/about' :
        require __DIR__ . '/views/about.php';
        break;
    default:
        http_response_code(404);
        require __DIR__ . '/views/404.php';
        break;
}

和目录结构 Directory Structure

现在,当我尝试打开 /about 或 /contact 时,它会将我重定向到 localhost/dashboard

有人可以帮我解决这个问题吗?

打开位于此处的 httpd-vhosts.conf 文件:C:\XAMPP\apache\conf\extra\httpd-vhosts.conf

在目录标记下添加以下行:

AllowOverride All

将您的 .htaccess 规则更改为

RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]

试试这个(如果您想稍后使用 images/js/css/.. 也很有帮助)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)\.(gif|jpg|png|jpeg|css|js|swf)$ /. [END,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php? [L,QSA]

Hint: You can combine the cases '/' and '

<?php

$request = $_SERVER['REQUEST_URI'];
echo $request;
switch ($request) {
    case '/' :
    case '' : // you can combine the cases '/' and ''
        require __DIR__ . '/views/home.php';
        break;
    case '/about' :
        require __DIR__ . '/views/about.php';
        break;
    default:
        http_response_code(404);
        require __DIR__ . '/views/404.php';
        break;
}