Yii 2.0 Framework Creating SEO Friendly URL

Yii 2.0 Framework Creating SEO Friendly URL


Yii 2.0 framework has a major improvement over version 1.1. Creating SEO friendly URL in Yii 2.0 framework has been a lot easier. All is just turning pretty url ‘on‘ to your Yii application and writing very few rewrite rules in htaccess file, enough to hide index.php from your URL and to make them SEO friendly.

At the time to writing the post the Yii framework version 2.0 Beta has been released and I have used default installation to let these seo friendly URL work on local development server at port 8080. Follow this two steps article to turn pretty urls on.

Step 1: Define component in your config file

After successful installation of Yii, you can see application home page as given:

yii-seo-friendly-url-1024x760

If you click on About link to visit about page in your site, your browser url will have index.php and get parameters according to path of your installation:

http://localhost:8080/ymanual/basic/web/index.php?r=site/about

Go to config folder under your directory and modify $config array by setting  enablePrettyUrl to true and showScriptName to false for urlManager component.
$config = [
‘id’ => ‘ymanual’,
‘basePath’ => dirname(DIR),
‘bootstrap’ => [‘log’],
‘extensions’ => require(DIR . ‘/../vendor/yiisoft/extensions.php’),
‘components’ => [
‘urlManager’ => [
‘enablePrettyUrl’ => true,
‘showScriptName’ => false,
],
‘request’ => [
// !!! insert a secret key in the following (if it is empty) – this is required by cookie validation
‘cookieValidationKey’ => ‘YOUR RANDOM KEY’,
],

Assigning showScriptName to false will hide index.php bootstrap file of Yii to appear in URL.

Step 2: Specify RewriteRule in htaccess

If you are at local web server then create a file called .htaccess, put the follow code into this and save this file under web folder in your application installation. For me this is htdocs > ymanual > basic > web. This will force every request to pass through index.php bootstrap file of Yii except except static resources like images.
RewriteEngine on

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

On a production server you should made the following configuration in Apache’shttpd.conf file or within a virtual host configuration.

Set document root to be “basic/web”

DocumentRoot “path/to/basic/web”

<Directory “path/to/basic/web”>
RewriteEngine on

If a directory or a file exists, use the request directly

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

Otherwise forward the request to index.php

RewriteRule . index.php

…other settings…

</Directory>

Necessarily replace path/to/basic/web with your actual for basic/web.

After making those adjustment you can access your site with SEO friendly URL in Yii 2.0 as given:
//Localhost
http://localhost:8080/ymanual/basic/web/about

//Production
http://yourdomain.com/about

Leave a comment