客户门户的 yii2 重写规则

yii2 rewrite rule for customer portal

我有一个带有前端和后端的 yii 高级应用程序。

我想实现的是,我可以用客户的名字访问前端。

示例(本地):http://localhost/myproject/frontend/web/customer1 应在第一次访问时变为 http://localhost/myproject/frontend/web/customer1/site/login

并且在登录后客户的名字应该留在 URL。目前 URL 在登录后更改为 http://localhost/myproject/frontend/web/

信息: customer 是一个 GET 参数。它应该始终是 http://localhost/myproject/frontend/web/ 之后的第一个参数,但我不想在每个重定向或自定义 link 中指定参数。我希望有一种方法可以保留此参数并将其传递给以下每个站点更改。

到目前为止我尝试过的:

'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'enableStrictParsing' => true, 
            'rules' => [
                '<controller>/<action>' => '<controller>/<action>',
                '<customer:\w+>' => '/site/login',
            ]
        ],

但这不起作用。我只能访问登录页面,之后 URL.

中不再显示客户名称

我的 .htaccess 文件如下所示:

RewriteEngine on

# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

非常感谢有关此主题的任何提示。

要将客户名称添加到所有 url 修改您的 url 规则:

<customer:\w+>/<controller>/<action>' => '<controller>/<action>,

如果您现在调用 yii\helpers\Url::to(['site/index', 'customer' => 'customer']),输出将如您所愿 - /customer/site/index

然而在整个项目中这样调用它是不灵活的方法。

大多数时候 Url::to() 方法用于生成内部 urls。

如果您在 $route 中传递数组,它将调用 Url::toRoute()。因此,您可以简单地在自定义组件中覆盖该方法。

namespace frontend\components;

use yii\helpers\Url as BaseUrl;

class Url extends BaseUrl
{
    public static function toRoute($route, $scheme = false)
    {
        $customer = ... // Get saved after login customer name (for example from the session)
        $route['customer'] = $customer;

        return parent::toRoute($route, $scheme);
    }
}

然后您只需调用 frontend\components\Url::to(['site/index']) 即可获得相同的结果。

官方文档 here.

中描述的自定义助手的替代方法 类

更新:

此外,此 url 规则 '<customer:\w+>' => '/site/login', 是多余的,url 应该只是 site/login,因为登录前的任何用户都是来宾。