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?
enablePrettyUrl=== true
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With