yii2 - 后端和后端前端到控制器配置文件+ .htaccess - COMPLETLY CONFIGURATION

时间:2018-05-30 08:45:04

标签: php .htaccess yii2 frontend backend

我正在尝试使用.htaccess文件和两个链接/按钮或重定向来完全管理我的页面:

  • 一个从前端到后端
  • 一个从后端到前端

希望这显然足够了。

我的环境是DEV,因为我在这里工作,如果情况那么差异。

我尝试过的所有内容:

我对.htaccess文件和urlManager感到困惑,所以非常感谢任何帮助。

让我们检查文件:

DIRECTORY ROOT& COMMON

/。htacces

#prevent directory listing
Options -Indexes
IndexIgnore */*

#follow symbolic links
Options FollowSymlinks
RewriteEngine on
RewriteRule ^admin(/.+)?$ backend/web/$1 [L,PT]
RewriteRule ^(.+)?$ frontend/web

/common/config/main.php

  return [
    'aliases' => [
        '@bower' => '@vendor/bower-asset',
        '@npm'   => '@vendor/npm-asset',
    ],
    'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
    'components' => [
        'cache' => [
            'class' => 'yii\caching\FileCache',
        ],
    ],
];

FRONTEND& FRONTEND CONTROLLER

/frontend/.htacces

RewriteEngine on

#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#otherwise, forward to index.php
RewriteRule . index.php

/frontend/config/main.php

$params = array_merge(
    require __DIR__ . '/../../common/config/params.php',
    require __DIR__ . '/../../common/config/params-local.php',
    require __DIR__ . '/params.php',
    require __DIR__ . '/params-local.php'
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        // main - used to generate and parse URLs to frontend from 
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => '/frontend/web',
            'rules' => [
                '/' => 'site/index',
                'home' => 'site/home',
                'about' => 'site/about',
                'moje-prace' => 'site/moje-prace',
                'umow-wizyte' => 'rezerwacje/create',
                'contact' => 'site/contact',
                'login' => 'site/login',
                'signup' => '/site/signup',
            ],
        ],
// slave - used to generate URLs to backend from frontend app
        'urlManagerBackend' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => '/admin',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
        ]

        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
    ],
    'params' => $params,
];

/frontend/controllers/SiteController.php

namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;

/**
 * Site controller
 */
class SiteController extends Controller
{

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'index', 'home', 'contact', 'about'],
                'rules' => [
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['home'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['contact'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    [
                        'actions' => ['about'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }


    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        if (!Yii::$app->user->isGuest) {

            $this->layout = 'main';

            return $this->render('home');
        }

        return $this->goHome();
    }


    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionHome()
    {
        return $this->render('home');
    }


    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        $this->layout = 'welcome';

        if (!Yii::$app->user->isGuest) {

            $this->layout = 'main';

            return $this->render('home');
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {

            $this->layout = 'main';

            return $this->render('home');
        }
        else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {

                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            }
            else {

                Yii::$app->session->setFlash('error', 'There was an error sending your message.');
            }

            return $this->refresh();
        }
        else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {

        $this->layout = 'welcome';

        $model = new SignupForm();

        if ($model->load(Yii::$app->request->post())) {

            if ($user = $model->signup()) {

                if (Yii::$app->getUser()->login($user)) {

                    $this->layout = 'main';

                    return $this->actionHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

BACKEND& BACKEND CONTROLLER

/backend/.htacces

RewriteEngine on

#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#otherwise, forward to index.php
RewriteRule . index.php

/backend/config/main.php

$params = array_merge(
    require __DIR__ . '/../../common/config/params.php',
    require __DIR__ . '/../../common/config/params-local.php',
    require __DIR__ . '/params.php',
    require __DIR__ . '/params-local.php'
);

return [
    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'backend\controllers',
    'bootstrap' => ['log'],
    'homeUrl' => '/administrator',
    'modules' => [],
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-backend',
            'baseUrl' => '/administrator',
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],
        'session' => [
            // this is the name of the session cookie used for login on the backend
            'name' => 'advanced-backend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
// main - used to generate and parse URLs to backend from backend app
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => '/backend/web',
        ],
// slave - used to generate URLs to frontend from backend app
        'urlManagerFrontend' => [
            'class' => 'yii\web\urlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => '/',
            'rules' => [
                '/' => 'site/index',
                'home' => 'site/home',
                'about' => 'site/about',
                'moje-prace' => 'site/moje-prace',
                'umow-wizyte' => 'rezerwacje/create',
                'contact' => 'site/contact',
                'login' => 'site/login',
                'signup' => 'site/signup',
            ],
    ],
    'params' => $params,
];

/backend/controllers/SiteController.php

namespace backend\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['logout', 'index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            $model->password = '';

            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }
}

VHOST&的apache.conf

apache2.conf

<Directory />
        Options FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

<Directory /usr/share>
        AllowOverride All
        Require all granted
</Directory>

<Directory /home/user/project>
        Options FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

虚拟主机

<VirtualHost *:80>
    ServerAdmin admin@prst.app
    ServerName pp.test
    DocumentRoot /home/user/project/pp/

<Directory "/home/user/project/pp/">
    Options FollowSymLinks
        AllowOverride All
        Require all granted
</Directory>

    ErrorLog ${APACHE_LOG_DIR}/pp__error.log
    CustomLog ${APACHE_LOG_DIR}/pp_access.log combined

</VirtualHost>

我无法在视图中创建超链接或在控制器中从前端到后端以及从后端到前端重定向。

2 个答案:

答案 0 :(得分:0)

我假设您的前端位于http://localhosts而您的后端位于http://localhosts/admin。如果您的重写规则无法正常运行,您可以尝试使用use symlinks - 至少对我来说,在共享主机上处理前端/后端URL总是更简单,更少问题。

您总是有2个UrlManager组件:main(对于当前环境)和slave(对于第二个环境,例如对于前端应用程序中的后端)。所以在frontend/config/main.php中你会有类似的东西:

// ...
// main - used to generate and parse URLs to frontend from frontend app
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'baseUrl' => '/',
    'rules' => [
        '/' => 'site/index',
        'home' => 'site/home',
        'about' => 'site/about',
        'moje-prace' => 'site/moje-prace',
        'umow-wizyte' => 'rezerwacje/create',
        'contact' => 'site/contact',
        'login' => 'site/login',
        'signup' => 'site/signup',
    ],
],
// slave - used to generate URLs to backend from frontend app
'urlManagerBackend' => [
    'class' => 'yii\web\urlManager',
    'baseUrl' => '/admin',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
],
// ...

backend/config/main.php

// ...
// main - used to generate and parse URLs to backend from backend app
'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'baseUrl' => '/admin',
],
// slave - used to generate URLs to frontend from backend app
'urlManagerFrontend' => [
    'class' => 'yii\web\urlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'baseUrl' => '/',
    'rules' => [
        '/' => 'site/index',
        'home' => 'site/home',
        'about' => 'site/about',
        'moje-prace' => 'site/moje-prace',
        'umow-wizyte' => 'rezerwacje/create',
        'contact' => 'site/contact',
        'login' => 'site/login',
        'signup' => 'site/signup',
    ],
],
// ...

正如您所看到的,他们已经交换了 - 来自前端应用的主UrlManager是后端应用中的奴隶。根据当前和目标环境,您使用不同的网址管理器。

如果您要从后端应用生成前端的网址:

Yii::$app->urlManagerFrontend->createUrl('site/index');
// result: http://localhost

如果您想从后端应用生成后端的网址:

Yii::$app->urlManager->createUrl('site/index');
// result: http://localhost/admin/site/index

如果您想从前端应用生成后端的网址:

Yii::$app->urlManagerBackend->createUrl('site/index');
// result: http://localhost/admin/site/index

如果您想从前端应用生成前端的网址:

Yii::$app->urlManager->createUrl('site/index');
// result: http://localhost

答案 1 :(得分:0)

最后它完成了!在新鲜的yii2高级版上我设置了前端和后端之间的连接,但是在两个“边”中仍然存在漂亮网址的问题。

<强>后端/ htaccess的

RewriteEngine on

#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#otherwise, forward to index.php
RewriteRule . index.php

<强>后端/配置/ main.php

use \yii\web\Request;
$baseUrl = str_replace('/backend/web', '/backend/web', (new Request)->getBaseUrl());
$frontEndBaseUrl = str_replace('/backend/web', '/frontend/web', (new Request)->getBaseUrl());

$params = array_merge(
    require __DIR__ . '/../../common/config/params.php',
    require __DIR__ . '/../../common/config/params-local.php',
    require __DIR__ . '/params.php',
    require __DIR__ . '/params-local.php'
);

return [
    'id' => 'app-backend',
    'basePath' => dirname(__DIR__),
    'controllerNamespace' => 'backend\controllers',
    'bootstrap' => ['log'],
    'modules' => [],
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-backend',
        ],

'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-backend', 'httpOnly' => true],
        ],

        'session' => [
            // this is the name of the session cookie used for login on the backend
            'name' => 'advanced-backend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],


// main - used to generate and parse URLs to backend from backend app
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => '/backend/web',
        ],
// slave - used to generate URLs to frontend from backend app
        'urlManagerFrontend' => [
            'class' => 'yii\web\urlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => '/',
            'rules' => [
                '/' => 'site/index',
                'home' => 'site/home',
                'about' => 'site/about',
                'moje-prace' => 'site/moje-prace',
                'umow-wizyte' => 'rezerwacje/create',
                'contact' => 'site/contact',
                'login' => 'site/login',
                'signup' => 'site/signup',
            ],
        ],
    ],
    'params' => $params,
];

前端的后端链接

只需创建:

$frontendUrl= Yii::$app->urlManagerFrontend->createUrl('//');
echo yii\helpers\Html::a('link to frontend', $frontendUrl);



<强>前端/ htaccess的

RewriteEngine on

#if directory or a file exist, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

#otherwise, forward to index.php
RewriteRule . index.php

<强>前端/配置/ main.php

use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '/frontend/web', (new Request)->getBaseUrl());
$backEndBaseUrl = str_replace('/frontend/web', '/backend/web', (new Request)->getBaseUrl());


$params = array_merge(
    require __DIR__ . '/../../common/config/params.php',
    require __DIR__ . '/../../common/config/params-local.php',
    require __DIR__ . '/params.php',
    require __DIR__ . '/params-local.php'
);

return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
    'components' => [
        'request' => [
            'csrfParam' => '_csrf-frontend',
        ],
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
            'identityCookie' => ['name' => '_identity-frontend', 'httpOnly' => true],
        ],
        'session' => [
            // this is the name of the session cookie used for login on the frontend
            'name' => 'advanced-frontend',
        ],
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],

// main - used to generate and parse URLs to frontend from frontend app
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'baseUrl' => $baseUrl,
            'rules' => [
                '/' => 'site/index',
                '/home' => 'site/home',
                '/about' => 'site/about',
                'moje-prace' => 'site/moje-prace',
                'umow-wizyte' => 'rezerwacje/create',
                'contact' => 'site/contact',
                'login' => 'site/login',
                'signup' => '/site/signup',
            ],
        ],
// slave - used to generate URLs to backend from frontend app
        'urlManagerBackend' => [
            'class' => 'yii\web\urlManager',
            'baseUrl' => $backEndBaseUrl,
            'enablePrettyUrl' => false,
            'showScriptName' => false,
        ],

    ],
    'params' => $params,
];

后端的前端链接

只需创建:

$backendUrl= Yii::$app->urlManagerBackend->createUrl('//');
echo yii\helpers\Html::a('link to backend', $backendUrl);

在根目录中,http://localhost/app-name/表示我创建了index.php文件,用于在点击后端链接(到前端)时重定向到前端:

<强>的index.php

header("Location: http://pp.test/frontend/web/", true, 301);
exit();

现在它的工作原理如此,但是我无法在后端启用漂亮的URL,因为它不能正常工作。而且我也不认为这是使用从其他文件重定向的好方法,特别是从根目录。

请注意,在common / config / main.php中,不需要进行任何更改,也不需要根目录中的.htaccess文件。