Using Yii returnUrl on nginx server

2020-02-15 08:32发布

问题:

I'm using nginx server with Yii application.

My problem is that the value of Yii::app()->user->returnUrl , in my SiteController.php , which redirect me after a successful login is always - mysite/index.php , regardless of which page I came from.

How can i fix it to be the value of the previous page URL ?

回答1:

That's the default behavior you are seeing, if you want to change that there are some choices! The same part in these choices is that you should extend CWebUser and add the functionalities

class WebUser extends CWebUser
{
}

& you need and mention it in the config

'user'=>array(
    'class' => 'WebUser',
    'loginUrl' => array('user/login'),
    'defaultDashboard' => array('user/dashboard'),
)

done, now the choices! if the returnUrl you want is fixed set it in function beforeLogin, you should override this function in the WebUser class and set the returnUrl manually, more info at Official API for CWebUser. But if returnUrl is not fixed & you want it to be set almost for every action which needs login then you should override the loginRequired function

public function loginRequired() {
    $app=Yii::app();
    $request=$app->getRequest();
    $controller=$app->controller;
    $actionParameters=$controller->actionParams;

    if(!$request->getIsAjaxRequest()) {
        if(empty($actionParameters))
            $this->setReturnUrl(array($controller->route));
        else
            $this->setReturnUrl(array($controller->route,$actionParameters));
    }
    if(($url=$this->loginUrl)!==null) {
        if(is_array($url)) {
            $route=isset($url[0]) ? $url[0] : $app->defaultController;
            $url=$app->createUrl($route,array_splice($url,1));
        }
        $request->redirect($url);
    }
    else
        throw new CHttpException(403,Yii::t('yii','Login Required'));
}

& the last step prevent loop after successful login

if($model->validate() && $model->login()){
    $returnUrl=Yii::app()->user->returnUrl;
    $url=(is_array($returnUrl))?$returnUrl[0]:$returnUrl;
    if(isset($returnUrl)&&stripos(strtolower($url),'logout')==false&&stripos(strtolower($url),'login')==false) {
        $this->redirect($this->createUrl($returnUrl[0],$returnUrl[1]));
    } else {
        $this->redirect($this->createUrl($returnUrl[0],$returnUrl[1]));
    }