2

我正在寻找一种在发送请求之前修改请求 URL 的方法。例如,以下 URL 应由相同的控制器/操作处理:

/en/paris
/de/paris
/paris

如果存在国家代码,我想捕获它,然后在没有它的情况下重写 URL,以便控制器不必处理它。我尝试了“dispatch:beforeDispatchLoop”事件,但它并没有为此设计。

任何的想法?

4

1 回答 1

1

如果您可以约定所有国家/地区代码在路径中排在第一位,那么附加的重写规则可能会帮助您:

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^([a-z]{2})/(.*)$ index.php?_lang=$1&_url=/$2 [QSA,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php?_url=/$1 [QSA,L]
</IfModule>

编辑

如果你真的需要在PHP中这样做,我建议你尽早截取国家代码,以免破坏默认路由行为(即需要手动编写所有路由)。一种方法是在主 DI 中设置共享服务来替换默认'router'服务。自定义路由器仅包含在Phalcon\Mvc\Router的子级中,其方法getRewriteUri被某些您想要的东西覆盖,它们只返回不带国家代码部分的 URI:

namespace MyApp\Services;

use Phalcon\Mvc\Router as PhRouter;

class Router extends PhRouter
{
    public function getRewriteUri()
    {
        $originalUri = parent::getRewriteUri();

        // Now you can:
        // Check if a country code has been sent and extract it
        // Store locale configurations to be used later
        // Remove the country code from the URI

        return $newUri;
    }
}
于 2014-12-09T20:30:28.193 回答