PHP框架中的漂亮URL

PHP框架中的漂亮URL,php,apache,mod-rewrite,url-rewriting,Php,Apache,Mod Rewrite,Url Rewriting,我知道可以在htaccess中添加规则,但我看到PHP框架不能做到这一点,而且不知何故,您仍然拥有漂亮的url。如果服务器不知道URL规则,他们怎么做 我一直在寻找,但我不明白它是如何做到的。这通常是通过将所有请求路由到单个入口点(一个根据请求执行不同代码的文件)来完成的,规则如下: # Redirect everything that doesn't match a directory or file to index.php RewriteCond %{REQUEST_FILENAME} !

我知道可以在htaccess中添加规则,但我看到PHP框架不能做到这一点,而且不知何故,您仍然拥有漂亮的url。如果服务器不知道URL规则,他们怎么做


我一直在寻找,但我不明白它是如何做到的。

这通常是通过将所有请求路由到单个入口点(一个根据请求执行不同代码的文件)来完成的,规则如下:

# Redirect everything that doesn't match a directory or file to index.php
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* index.php [L]
然后,该文件将请求(
$\u SERVER[“request\u URI”]
)与路由列表进行比较,路由列表是将请求匹配到控制器操作(在MVC应用程序中)或其他执行路径的模式映射。框架通常包括一个路由,可以从请求本身推断控制器和操作,作为备份路由

一个简单的小例子:

<?php

// Define a couple of simple actions
class Home {
    public function GET() { return 'Homepage'; }
}

class About {
    public function GET() { return 'About page'; }
}

// Mapping of request pattern (URL) to action classes (above)
$routes = array(
    '/' => 'Home',
    '/about' => 'About'
);

// Match the request to a route (find the first matching URL in routes)
$request = '/' . trim($_SERVER['REQUEST_URI'], '/');
$route = null;
foreach ($routes as $pattern => $class) {
    if ($pattern == $request) {
        $route = $class;
        break;
    }
}

// If no route matched, or class for route not found (404)
if (is_null($route) || !class_exists($route)) {
    header('HTTP/1.1 404 Not Found');
    echo 'Page not found';
    exit(1);
}

// If method not found in action class, send a 405 (e.g. Home::POST())
if (!method_exists($route, $_SERVER["REQUEST_METHOD"])) {
    header('HTTP/1.1 405 Method not allowed');
    echo 'Method not allowed';
    exit(1);
}

// Otherwise, return the result of the action
$action = new $route;
$result = call_user_func(array($action, $_SERVER["REQUEST_METHOD"]));
echo $result;

查看我的答案大多数框架所做的是将所有请求重定向到一个处理所有内容的文件。链接(实际上)已断开(缺少源代码)。是吗?在您的代码中,您忘记了:要在GET params:
RewriteRule(.*)index.php中添加url?url=$1[QSA,L]
嗨,Olivier,没有必要将url作为参数传递,因为它在
$\u服务器['REQUEST\u URI']
中可用。您确定它不会是最终重写的url(即
$\u服务器['REQUEST\u URI']
=
index.php
)?