yii2 urlManager enablePrettyUrl not working
Asked Answered
C

2

5

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
Compline answered 7/1, 2015 at 19:50 Comment(0)
P
8

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.

Playmate answered 8/1, 2015 at 4:37 Comment(2)
Oh Thanks. So, this is just a misunderstanding about pretty url's! Indeed, I was looking for /book/read/booktitle/chaptertitle. Did this change between Yii 1.1 and Yii 2?Compline
Not really, I believe they work in the same way. You still need to define URL rules for both of them from what I remember.Playmate
C
1

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.

Catalinacatalo answered 8/1, 2015 at 5:56 Comment(1)
How can you hit it like that? It worked like that in Yii 1 (urlFormat=path), whereas I don't think it works like that in yii 2 aloneBosomed

© 2022 - 2024 — McMap. All rights reserved.