0

Хочу сделать ЧПУ на yii2. Сделал всё по инструкции, но ничего не работает, к тому же отображается только главная страница, а остальные (about, contact, login) - нет, выдаётся ошибка 404. Подскажите, что может быть не так? Содержимое корневого .htaccess:

    RewriteEngine on
    RewriteRule ^(.+)?$ /web/$1

Содержимое web/.htaccess:

    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php

Содержимое config/web.php:

    <?php

    $params = require __DIR__ . '/params.php';
    $db = require __DIR__ . '/db.php';

    $config = [
        'id' => 'basic',
        'basePath' => dirname(__DIR__),
        'bootstrap' => ['log'],
        'aliases' => [
            '@bower' => '@vendor/bower-asset',
            '@npm'   => '@vendor/npm-asset',
        ],
        'components' => [
        'request' => [
                // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
               'cookieValidationKey' => 'cukfdukfudytdgfcfxrt',
               //'baseUrl' => '',
          ],
         'cache' => [
              'class' => 'yii\caching\FileCache',
          ],
          'user' => [
          'identityClass' => 'app\models\User',
          'enableAutoLogin' => true,
         ],
         'errorHandler' => [
              'errorAction' => 'site/error',
            ],
         'mailer' => [
              'class' => 'yii\swiftmailer\Mailer',
              // send all mails to a file by default. You have to set
              // 'useFileTransport' to false and configure a transport
              // for the mailer to send real emails.
              'useFileTransport' => true,
          ],
          'log' => [
              'traceLevel' => YII_DEBUG ? 3 : 0,
              'targets' => [
                 [
                       'class' => 'yii\log\FileTarget',
                       'levels' => ['error', 'warning'],
                 ],
               ],
            ],
           'db' => $db,

           'urlManager' => [
           'enablePrettyUrl' => true,
           'showScriptName' => false,
           'rules' => [
             ],
          ],

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

  if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
    'class' => 'yii\debug\Module',
    // uncomment the following to add your IP if you are not connecting from localhost.
    //'allowedIPs' => ['127.0.0.1', '::1'],
];

$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
    'class' => 'yii\gii\Module',
    // uncomment the following to add your IP if you are not connecting from localhost.
    //'allowedIPs' => ['127.0.0.1', '::1'],
];
 }

   return $config;
5

3 ответа 3

1

в корне. Правила сразу с переводом на https (автоматически сработает, если будет защищённое соединение)

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
</IfModule>

<IfModule mod_rewrite.c>
    RewriteCond %{HTTP_HOST} ^www\.(.*) [NC]
    RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

    RewriteCond %{REQUEST_URI} ^/.*
    RewriteRule ^(.*)$ web/$1 [L]
    RewriteCond %{REQUEST_URI} !^web/
    RewriteCond %{REQUEST_FILENAME} !-f [OR]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ web/index.php

    RewriteCond %{HTTPS} off
    RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>

В папке web

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . index.php

в config/web.php нужно раскомментировать (у вас не так в примере) строку 'baseUrl' => '',

Там же нужно добавить правила. Например:

'rules' => [
    '<action:(about|contact|login|)>' => '/site/<action>',
    '<controller>/<action>' => '<controller>/<action>',
],

Отмечу, что все экшены (кроме actionIndex) на страницы нужно указывать через |. Всё.

0

Нужно добавить в urlManager правила. И только тогда все заработает. Как Вы хотите чтобы yii2 само знало какие страницы по какому адресу отображать. В 'rules' нужно указать все ето. 'желаемый_адрес' => 'контроллер/действие'

0

В моем случае не работало из-за настроек nginx (mac OS). В файле настроек сервера по адресу: /usr/local/etc/nginx/nginx.conf

строка: try_files $uri $uri/ /index.php?$args;

location / {
        # Перенаправляем все запросы к несуществующим директориям и файлам на 
        index.php
        try_files $uri $uri/ /index.php?$args;
    }

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.