Yii2 Custom url management. Getting 400 error

Pepito Fernandez picture Pepito Fernandez · Apr 10, 2014 · Viewed 13.8k times · Source

Well, PHP times.

My client wants me to use Yii2 as the framework for his project.

I got it up and running. No problem. I used the advanced template via composer.

Set my web root to /frontend/web, etc.

NOW, i want to use this url format

website.com/messages/ or website.com/messages/tom... etc.

Right now the way is setup shows website.com/index.php?r=messages/index...

I found this documentation...

https://github.com/yiisoft/yii2/blob/master/docs/guide/url.md

But i can't seem to get it straight.

Here are my steps...

I configured my apache server to point to /usr/www/payroll/frontend/web/

I added to my web folder a .htaccess file with this content.

RewriteEngine on

# If a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward it to index.php
RewriteRule . index.php

I also added the component 'urlManager' as in the directions. It seems to catch the request and modify it.

'components'=>[
    'urlManager' => [
            'class' => 'yii\web\UrlManager',
            'enablePrettyUrl' => true,
            'showScriptName' => 'false'
        ],
],

For example if I type website.com you can see it adds /site/index to the url. (without the url component active it simply adds /index.php?site/index)

So, obviously there's a modification perfomed to the url (via UrlManager) but I get 404 error

I am running out of ideas here. I am new to Php, Apache and Yii2. Any help, Greatly appreciated.

Thanks

Answer

d.raev picture d.raev · Jul 16, 2014

To make pretty URL working on Yii 2.0 you need 2 things:

1: Edit /frontend/config/main.php (or the appropriate main config in your case) and add:

'components'=>[
        'urlManager' => [
                'class' => 'yii\web\UrlManager',
                'enablePrettyUrl' => true,
                'showScriptName' => false,
            ],
    ],

2: Add a .htaccess file in YOUR WEB ROOT folder. In yii 2.0 advanced this is NOT project root directory but instead: /frontend/web

.htaccess example:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php