Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

yii2 urlManager enablePrettyUrl not working

In Yii2, I cannot enable pretty url's.

My config:

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

My .htaccess:

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

My script:

echo 'enablePrettyUrl: ';
echo Yii::$app->urlManager->enablePrettyUrl ? 'true ' : 'false';

echo '<br>';
echo 'enableStrictParsing: ';
echo Yii::$app->urlManager->enableStrictParsing ? 'true ' : 'false';

echo '<br>';
echo 'showScriptName: ';
echo Yii::$app->urlManager->showScriptName ? 'true ' : 'false';

echo Url::to(['/book/read', 't' => 'booktitle', 'c'=>'chaptertitle']);

The output from the script:

enablePrettyUrl: true
enableStrictParsing: false
showScriptName: false

/book/read?t=booktitle&c=chaptertitle

Clearly, I am not getting pretty Url's. Why not?

  • We know enablePrettyUrl=== true
  • I do not believe there is anything wrong with my .htaccess
like image 797
Ivo Renkema Avatar asked Jan 07 '15 19:01

Ivo Renkema


2 Answers

You are getting pretty URLs. This is a pretty url

/book/read?t=booktitle&c=chaptertitle

An ugly URL is

index.php?r=book/read&t=booktitle&c=chaptertitle

So everything works as expected in yii2. Now you may want to make them prettier still, in this case you can add to your rule section something like

'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        'book/read/<t>/<c>' => 'book/read',
    ]

This would generate a link that will look like

book/read/booktitle/chaptertitle

Change it to suit your needs. No need to change anything in the controller, it will still receive the t and c parameters.

like image 158
Mihai P. Avatar answered Sep 25 '22 16:09

Mihai P.


you are already getting pretty URL

/book/read?t=booktitle&c=chaptertitle

is a pretty url. you can also hit it like this

/book/read/t/booktitle/c/chaptertitle

if you want in browser it will result in same, if you are confusing yourself with ? in URL.

like image 37
Kuldeep Dangi Avatar answered Sep 23 '22 16:09

Kuldeep Dangi