За последние 24 часа нас посетили 22384 программиста и 1023 робота. Сейчас ищут 669 программистов ...

Yii2, ошибка 404 после установки 'enablePrettyUrl' => true

Тема в разделе "Yii", создана пользователем 118_64, 9 май 2020.

Метки:
  1. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    Установил Yii2 на localhost, главная страница доступна по адресам http://localhost/web/site/index и http://localhost/web/

    Включил ЧПУ, добавив в конфигурацию в файле app\config\web.php строки:
    PHP:
    1. 'urlManager' => [
    2.     'enablePrettyUrl' => true,
    3.     'enableStrictParsing' => true,
    4.     'showScriptName' => false,
    5.     'rules' => [
    6.         ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    7.     ],
    8. ]
    Yii вообще не "подхватывается", голый экран с ошибкой 404 при попытке доступа: на http://localhost/users
    PHP:
    1. HTTP/1.1 404 Not Found
    2. Date: Fri, 08 May 2020 22:11:15 GMT
    3. Server: Apache/2.4.41 (Win64) PHP/7.4.1
    4. Content-Length: 196
    5. Content-Type: text/html; charset=iso-8859-1
    6. <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
    7. <html><head>
    8. <title>404 Not Found</title>
    9. </head><body>
    10. <h1>Not Found</h1>
    11. <p>The requested URL was not found on this server.</p>
    12. </body></html>
    Также 404 ошибка отдается при попытке доступа на http://localhost/web/site/index В этом случае сам Yii2 подгружается:
    PHP:
    1. HTTP/1.1 404 Not Found
    2. Date: Fri, 08 May 2020 22:17:22 GMT
    3. Server: Apache/2.4.41 (Win64) PHP/7.4.1
    4. X-Powered-By: PHP/7.4.1
    5. Set-Cookie: PHPSESSID=grr3qdhuvjunhkiha9pbta7nh5; path=/; HttpOnly
    6. Expires: Thu, 19 Nov 1981 08:52:00 GMT
    7. Cache-Control: no-store, no-cache, must-revalidate
    8. Pragma: no-cache
    9. X-Debug-Tag: 5eb5da7214cd9
    10. X-Debug-Duration: 46
    11. X-Debug-Link: /web/debug/default/view?tag=5eb5da7214cd9
    12. Set-Cookie: _csrf=d8c98373e08722801f7165aef549cd072201f6e8ea458c462375da8c0e2f9b5ea%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22Kem2akrdboCh5WcjXpzRhVOD21wS0k2p%22%3B%7D; path=/; HttpOnly
    13. Transfer-Encoding: chunked
    14. Content-Type: text/html; charset=UTF-8
    Наличие/отсутствие .htaccess в корневой директории ни на что не повлияло.

    Всё делал по этому руководству - https://www.yiiframework.com/doc/guide/2.0/ru/rest-quick-start
    Насколько вижу, где-то сделал ошибку. Прошу подсказать, в чем ошибка.
     
  2. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Надо сделать локальный домен, натравленный на папку web
    --- Добавлено ---
    В доках есть конфиги и для апача, и для nginx-а, поищи
    --- Добавлено ---
    enableStrictParsing - это значит, отключить автоматическое распознавание урл как контроллер/акция, а позволять заходить только по урлам, прямо прописанным в конфиге
     
    118_64 нравится это.
  3. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    Спасибо за ответ. Указал в качестве корневой директории папку web, Yii "подхватывается", но обращение к http://localhost возвращает ошибку 404:
    Код (Text):
    1. curl -i -H "Accept:application/xml" "http://localhost"
    2. HTTP/1.1 404 Not Found
    3. Date: Sat, 09 May 2020 20:24:33 GMT
    4. Server: Apache/2.4.41 (Win64) PHP/7.4.1
    5. X-Powered-By: PHP/7.4.1
    6. Set-Cookie: PHPSESSID=ap134465v3lf133untkljt25lh; path=/; HttpOnly
    7. Expires: Thu, 19 Nov 1981 08:52:00 GMT
    8. Cache-Control: no-store, no-cache, must-revalidate
    9. Pragma: no-cache
    10. X-Debug-Tag: 5eb71181aa95d
    11. X-Debug-Duration: 51
    12. X-Debug-Link: /debug/default/view?tag=5eb71181aa95d
    13. Set-Cookie: _csrf=285e741ea5303bf0213c31ef8823b9d8147178065aec833c94a6966fad50b35aa%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22P0VLjdB5OLLeIsY6D1rFYTo0vKrd1F6-%22%3B%7D; path=/; HttpOnly
    14. Transfer-Encoding: chunked
    15. Content-Type: text/html; charset=UTF-8

    Обращение к http://localhost/users даёт ошибку 500:
    Код (Text):
    1. curl -i -H "Accept:application/xml" "http://localhost/users"
    2. HTTP/1.1 500 Internal Server Error
    3. Date: Sat, 09 May 2020 20:16:12 GMT
    4. Server: Apache/2.4.41 (Win64) PHP/7.4.1
    5. X-Powered-By: PHP/7.4.1
    6. Vary: Accept
    7. X-Debug-Tag: 5eb70f8cd6abf
    8. X-Debug-Duration: 35
    9. X-Debug-Link: /debug/default/view?tag=5eb70f8cd6abf
    10. Content-Length: 1124
    11. Connection: close
    12. Content-Type: application/xml; charset=UTF-8
    13.  
    14. <?xml version="1.0" encoding="UTF-8"?>
    15. <response><name>Exception</name><message>Call to undefined method app\models\User::find()</message><code>0</code><type>Error</type><file>E:\data\public\vendor\yiisoft\yii2\rest\IndexAction.php</file><line>114</line><stack-trace><item>#0 E:\data\public\vendor\yiisoft\yii2\rest\IndexAction.php(82): yii\rest\IndexAction-&gt;prepareDataProvider()</item><item>#1 [internal function]: yii\rest\IndexAction-&gt;run()</item><item>#2 E:\data\public\vendor\yiisoft\yii2\base\Action.php(94): call_user_func_array()</item><item>#3 E:\data\public\vendor\yiisoft\yii2\base\Controller.php(157): yii\base\Action-&gt;runWithParams()</item><item>#4 E:\data\public\vendor\yiisoft\yii2\base\Module.php(528): yii\base\Controller-&gt;runAction()</item><item>#5 E:\data\public\vendor\yiisoft\yii2\web\Application.php(103): yii\base\Module-&gt;runAction()</item><item>#6 E:\data\public\vendor\yiisoft\yii2\base\Application.php(386): yii\web\Application-&gt;handleRequest()</item><item>#7 E:\data\public\web\index.php(12): yii\base\Application-&gt;run()</item><item>#8 {main}</item></stack-trace></response>
    Правило 'controller'=>'user' прописано.
     
    #3 118_64, 9 май 2020
    Последнее редактирование: 9 май 2020
  4. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Покажи класс app\models\User и конфиг роутера
     
  5. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    app\models\User:
    PHP:
    1. <?php
    2.  
    3. namespace app\models;
    4.  
    5. class User extends \yii\base\BaseObject implements \yii\web\IdentityInterface
    6. {
    7.     public $id;
    8.     public $username;
    9.     public $password;
    10.     public $authKey;
    11.     public $accessToken;
    12.  
    13.     private static $users = [
    14.         '100' => [
    15.             'id' => '100',
    16.             'username' => 'admin',
    17.             'password' => 'admin',
    18.             'authKey' => 'test100key',
    19.             'accessToken' => '100-token',
    20.         ],
    21.         '101' => [
    22.             'id' => '101',
    23.             'username' => 'demo',
    24.             'password' => 'demo',
    25.             'authKey' => 'test101key',
    26.             'accessToken' => '101-token',
    27.         ],
    28.     ];
    29.  
    30.  
    31.     /**
    32.      * {@inheritdoc}
    33.      */
    34.     public static function findIdentity($id)
    35.     {
    36.         return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
    37.     }
    38.  
    39.     /**
    40.      * {@inheritdoc}
    41.      */
    42.     public static function findIdentityByAccessToken($token, $type = null)
    43.     {
    44.         foreach (self::$users as $user) {
    45.             if ($user['accessToken'] === $token) {
    46.                 return new static($user);
    47.             }
    48.         }
    49.  
    50.         return null;
    51.     }
    52.  
    53.     /**
    54.      * Finds user by username
    55.      *
    56.      * @param string $username
    57.      * @return static|null
    58.      */
    59.     public static function findByUsername($username)
    60.     {
    61.         foreach (self::$users as $user) {
    62.             if (strcasecmp($user['username'], $username) === 0) {
    63.                 return new static($user);
    64.             }
    65.         }
    66.  
    67.         return null;
    68.     }
    69.  
    70.     /**
    71.      * {@inheritdoc}
    72.      */
    73.     public function getId()
    74.     {
    75.         return $this->id;
    76.     }
    77.  
    78.     /**
    79.      * {@inheritdoc}
    80.      */
    81.     public function getAuthKey()
    82.     {
    83.         return $this->authKey;
    84.     }
    85.  
    86.     /**
    87.      * {@inheritdoc}
    88.      */
    89.     public function validateAuthKey($authKey)
    90.     {
    91.         return $this->authKey === $authKey;
    92.     }
    93.  
    94.     /**
    95.      * Validates password
    96.      *
    97.      * @param string $password password to validate
    98.      * @return bool if password provided is valid for current user
    99.      */
    100.     public function validatePassword($password)
    101.     {
    102.         return $this->password === $password;
    103.     }
    104. }

    web.php:
    PHP:
    1. <?php
    2.  
    3. $params = require __DIR__ . '/params.php';
    4. $db = require __DIR__ . '/db.php';
    5.  
    6. $config = [
    7.     'id' => 'basic',
    8.     'basePath' => dirname(__DIR__),
    9.     'bootstrap' => ['log'],
    10.     'aliases' => [
    11.         '@bower' => '@vendor/bower-asset',
    12.         '@npm'   => '@vendor/npm-asset',
    13.     ],
    14.     'components' => [
    15.         'request' => [
    16.             // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    17.             'cookieValidationKey' => 'a1TFc_oiNZ88_jThpbuyTO0OcmA3OC95',          
    18.             'parsers' => [
    19.                 'application/json' => 'yii\web\JsonParser',
    20.             ],
    21.             // 'baseUrl' => '',      
    22.         ],
    23.         'cache' => [
    24.             'class' => 'yii\caching\FileCache',
    25.         ],
    26.         'user' => [
    27.             'identityClass' => 'app\models\User',
    28.             'enableAutoLogin' => true,
    29.         ],
    30.         'errorHandler' => [
    31.             'errorAction' => 'site/error',
    32.         ],
    33.         'mailer' => [
    34.             'class' => 'yii\swiftmailer\Mailer',
    35.             // send all mails to a file by default. You have to set
    36.             // 'useFileTransport' to false and configure a transport
    37.             // for the mailer to send real emails.
    38.             'useFileTransport' => true,
    39.         ],
    40.         'log' => [
    41.             'traceLevel' => YII_DEBUG ? 3 : 0,
    42.             'targets' => [
    43.                 [
    44.                     'class' => 'yii\log\FileTarget',
    45.                     'levels' => ['error', 'warning'],
    46.                 ],
    47.             ],
    48.         ],
    49.         'db' => $db,
    50.  
    51.         'urlManager' => [
    52.             'enablePrettyUrl' => true,
    53.             'enableStrictParsing' => true,
    54.             'showScriptName' => false,
    55.             'rules' => [
    56.                 ['class' => 'yii\rest\UrlRule', 'controller' => 'user'],
    57.             ],
    58.         ],      
    59.     ],
    60.     'params' => $params,
    61. ];
    62.  
    63. if (YII_ENV_DEV) {
    64.     // configuration adjustments for 'dev' environment
    65.     $config['bootstrap'][] = 'debug';
    66.     $config['modules']['debug'] = [
    67.         'class' => 'yii\debug\Module',
    68.         // uncomment the following to add your IP if you are not connecting from localhost.
    69.         //'allowedIPs' => ['127.0.0.1', '::1'],
    70.     ];
    71.  
    72.     $config['bootstrap'][] = 'gii';
    73.     $config['modules']['gii'] = [
    74.         'class' => 'yii\gii\Module',
    75.         // uncomment the following to add your IP if you are not connecting from localhost.
    76.         //'allowedIPs' => ['127.0.0.1', '::1'],
    77.     ];
    78. }
    79.  
    80. return $config;

    yiisoft\yii2\web\UrlManager.php (не менял ничего, вероятно, именно здесь соответствующие строки нужно было раскомментировать?)
    PHP:
    1. <?php
    2. /**
    3. * @link http://www.yiiframework.com/
    4. * @copyright Copyright (c) 2008 Yii Software LLC
    5. * @license http://www.yiiframework.com/license/
    6. */
    7.  
    8. namespace yii\web;
    9.  
    10. use Yii;
    11. use yii\base\Component;
    12. use yii\base\InvalidConfigException;
    13. use yii\caching\CacheInterface;
    14. use yii\di\Instance;
    15. use yii\helpers\Url;
    16.  
    17. /**
    18. * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
    19. *
    20. * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
    21. * You can access that instance via `Yii::$app->urlManager`.
    22. *
    23. * You can modify its configuration by adding an array to your application config under `components`
    24. * as it is shown in the following example:
    25. *
    26. * ```php
    27. * 'urlManager' => [
    28. *     'enablePrettyUrl' => true,
    29. *     'rules' => [
    30. *         // your rules go here
    31. *     ],
    32. *     // ...
    33. * ]
    34. * ```
    35. *
    36. * Rules are classes implementing the [[UrlRuleInterface]], by default that is [[UrlRule]].
    37. * For nesting rules, there is also a [[GroupUrlRule]] class.
    38. *
    39. * For more details and usage information on UrlManager, see the [guide article on routing](guide:runtime-routing).
    40. *
    41. * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
    42. * @property string $hostInfo The host info (e.g. `http://www.example.com`) that is used by
    43. * [[createAbsoluteUrl()]] to prepend to created URLs.
    44. * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
    45. * URLs.
    46. *
    47. * @author Qiang Xue <qiang.xue@gmail.com>
    48. * @since 2.0
    49. */
    50. class UrlManager extends Component
    51. {
    52.     /**
    53.      * @var bool whether to enable pretty URLs. Instead of putting all parameters in the query
    54.      * string part of a URL, pretty URLs allow using path info to represent some of the parameters
    55.      * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
    56.      * "/index.php?r=news%2Fview&id=100".
    57.      */
    58.     public $enablePrettyUrl = false;
    59.     /**
    60.      * @var bool whether to enable strict parsing. If strict parsing is enabled, the incoming
    61.      * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
    62.      * Otherwise, the path info part of the request will be treated as the requested route.
    63.      * This property is used only when [[enablePrettyUrl]] is `true`.
    64.      */
    65.     public $enableStrictParsing = false;
    66.     /**
    67.      * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is `true`.
    68.      * This property is used only if [[enablePrettyUrl]] is `true`. Each element in the array
    69.      * is the configuration array for creating a single URL rule. The configuration will
    70.      * be merged with [[ruleConfig]] first before it is used for creating the rule object.
    71.      *
    72.      * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
    73.      * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
    74.      * array, one can use the key to represent the pattern and the value the corresponding route.
    75.      * For example, `'post/<id:\d+>' => 'post/view'`.
    76.      *
    77.      * For RESTful routing the mentioned shortcut format also allows you to specify the
    78.      * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
    79.      * You can do that  by prepending it to the pattern, separated by space.
    80.      * For example, `'PUT post/<id:\d+>' => 'post/update'`.
    81.      * You may specify multiple verbs by separating them with comma
    82.      * like this: `'POST,PUT post/index' => 'post/create'`.
    83.      * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
    84.      * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
    85.      * so you normally would not specify a verb for normal GET request.
    86.      *
    87.      * Here is an example configuration for RESTful CRUD controller:
    88.      *
    89.      * ```php
    90.      * [
    91.      *     'dashboard' => 'site/index',
    92.      *
    93.      *     'POST <controller:[\w-]+>' => '<controller>/create',
    94.      *     '<controller:[\w-]+>s' => '<controller>/index',
    95.      *
    96.      *     'PUT <controller:[\w-]+>/<id:\d+>'    => '<controller>/update',
    97.      *     'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
    98.      *     '<controller:[\w-]+>/<id:\d+>'        => '<controller>/view',
    99.      * ];
    100.      * ```
    101.      *
    102.      * Note that if you modify this property after the UrlManager object is created, make sure
    103.      * you populate the array with rule objects instead of rule configurations.
    104.      */
    105.     public $rules = [];
    106.  
    107.     // и т.д.
     
    denis01 нравится это.
  6. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    Сделал по этой инструкции, Yii2 корректно работает и обрабатывает ссылки в интерфейсе.
    Обращение к http://localhost/users продолжает возвращать 404:
    Код (Text):
    1. curl -i -H "Accept:application/xml" "http://localhost/users"
    2. HTTP/1.1 404 Not Found
    3. Date: Sun, 10 May 2020 11:31:46 GMT
    4. Server: Apache/2.4.41 (Win64) PHP/7.4.1
    5. X-Powered-By: PHP/7.4.1
    6. Set-Cookie: PHPSESSID=bfu1usjqt99kqtee49l5c47pqb; path=/; HttpOnly
    7. Expires: Thu, 19 Nov 1981 08:52:00 GMT
    8. Cache-Control: no-store, no-cache, must-revalidate
    9. Pragma: no-cache
    10. X-Debug-Tag: 5eb7e6221d249
    11. X-Debug-Duration: 51
    12. X-Debug-Link: /debug/default/view?tag=5eb7e6221d249
    13. Set-Cookie: _csrf=cf4d6c0cb459f58d06c1fa7125a4bb84e3b44515ba0028f35a3ea02358f6c4e5a%3A2%3A%7Bi%3A0%3Bs%3A5%3A%22_csrf%22%3Bi%3A1%3Bs%3A32%3A%22wPRgA94sr1YAIeps8_R_v__WrPjTcR8m%22%3B%7D; path=/; HttpOnly
    14. Transfer-Encoding: chunked
    15. Content-Type: text/html; charset=UTF-8
     
  7. denis01

    denis01 Суперстар
    Команда форума Модератор

    С нами с:
    9 дек 2014
    Сообщения:
    12.230
    Симпатии:
    1.715
    Адрес:
    Молдова, г.Кишинёв
    @118_64 обращение идёт к users, а класс user без s, или я что-то упустил?
     
  8. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    Пробовал. Обращение к user даёт тот же результат.
     
  9. mkramer

    mkramer Суперстар
    Команда форума Модератор

    С нами с:
    20 июн 2012
    Сообщения:
    8.553
    Симпатии:
    1.754
    Ну чтоб вызывать User::find(), User должен быть унаследован от ActiveRecord, а не BaseObject, это раз. Просто базовый шаблон приложения из коробки поставляется с примером аутентификации без БД.

    https://www.yiiframework.com/doc/api/2.0/yii-rest-urlrule

    В конроллере нужные методы есть?


    Вообще, странно. Ну я понимаю, с Laravel тут у многих проблемы, потому что английский никто нифига не учит. Ну у yii2 большая часть документации есть и на русском, в чём проблема внимательно прочитать её от корки до корки?
     
    118_64 нравится это.
  10. 118_64

    118_64 Активный пользователь

    С нами с:
    8 янв 2015
    Сообщения:
    84
    Симпатии:
    2
    Контроллер app\controllers\UserController.php из примера в документации. Больше в нём нет ничего.
    PHP:
    1. namespace app\controllers;
    2.  
    3. use yii\rest\ActiveController;
    4.  
    5. class UserController extends ActiveController
    6. {
    7.     public $modelClass = 'app\models\User';
    8. }
    С изучением Laravel больших проблем не возникло, многие вещи, читаемые в русскоязычной документации по Yii2, понимал только потому, что ранее это понял в Laravel. А вот тут уперся при выполнении примера из документации на этой странице.