yii2yii-url-manager

yii2 urlManager enablePrettyUrl not work with IndexController


My config:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<alias:login|logout>' => 'site/<alias>',
    ],
]

My .htaccess:

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

my controllers: my controllers

I tested example.com/home/test, example.com/login and example.com/index.php/index/test work, but example.com/index/test 404, I have to use example.com/index.php/index/test .

any suggestion will be appreciated.


Solution

  • On your htaccess file the first rewrite condition reads:

    "if the file is not directly found then..."

    This condition will fail and the rewrite rule won't get applied when requesting actions on IndexController

    The second reads: "if the directory is not directly found then..."

    The first condition fails because you named one of your controllers IndexController, it conflicts with the name of index.php.

    When you request an action on the HomeController the server first tries to find a home.html or home.php file, since it can't find it, it uses the rewrite rule and you get the expected result, the action on your controller runs.

    But, when you try to run index/test the server first tries to find index.html or index.php, the file is found so the rewrite rule doesn't get applied. Then the server tries to serve the index/test file but it can't find it and returns 404.

    You could rearrange your controllers, right now you have three home controllers, SiteController, HomeController and IndexController, do you really need the three of them?

    Otherwise might be able to change your rewrite rules somehow to make it work, but I'm not sure exactly how to do it, I would think that it would be something along the lines of making the first rewrite condition more strict to make sure that only matching the exact file path stops the rewriting.

    If you do modify .htaccess make sure afterwards that your static resources are still being served correctly.