【问题标题】:Pretty URLs in PHP frameworksPHP 框架中的漂亮 URL
【发布时间】:2012-01-16 10:48:27
【问题描述】:

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

我一直在寻找 Yii's url manager class 但我不明白它是如何做到的。

【问题讨论】:

标签: php apache mod-rewrite url-rewriting


【解决方案1】:

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

# 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]

然后,此文件将请求 ($_SERVER["REQUEST_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;

结合第一个配置,这是一个简单的脚本,允许您使用像domain.com/about 这样的 URL。希望这可以帮助您了解这里发生的事情。

【讨论】:

  • 在您的代码中您忘记了:在 GET 参数中添加 url:RewriteRule (.*) index.php?url=$1 [QSA,L]
  • 嗨 Olivier,实际上没有必要将 url 作为参数传递,因为它在 $_SERVER['REQUEST_URI'] 中可用。
  • 确定它不会是最终重写的 URL(即$_SERVER['REQUEST_URI']==index.php)吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-31
相关资源
最近更新 更多