Remove index.php from Yii project URL

on 04 April 2012
In this post, we'll learn how to remove the index.php from the url of a Yii project and thus make the urls more pretty and search engine friendly. Plus, they become more easy to remember. Yayyy!

Step 1 - Create htaccess

Open notepad or any other text editor, paste the following code into it :
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

RewriteBase /blog

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteCond $1 !^(index\.php)
RewriteRule ^(.+)$ index.php?$1 [PT,L,QSA]
Now on line 5 of this code, change the '/blog' with the project directory name of your project, suppose your project name is 'mywebapp' then line 5 should look like this:
RewriteBase /mywebapp
Now save this file as .htaccess in your project folder 'mywebapp', over here my project name was 'blog'.



Step 2 - enable mod_rewrite


Goto your apache directory, find the httpd.conf file, open it using notepad and find the following line:
#LoadModule rewrite_module modules/mod_rewrite.so
Edit that line and remove the # symbol to enable loading of the module in apache. The line should now look like this:
LoadModule rewrite_module modules/mod_rewrite.so



Step 3 - enable url overwriting


Now in the same httpd.conf file, search for the line
AllowOverride none
Modify it like this:
AllowOverride all
now save your file and close it.



Step 4 - edit your project configuration


Goto your Yii project directory and open the main.php file from config directory, find the following code:
'urlManager'=>array(
         'urlFormat'=>'path',
        ...
Modify it and add the following code on the third line:
'showScriptName'=>false,
Now your config file should be looking like this
'urlManager'=>array(
         'urlFormat'=>'path',
                'showScriptName'=>false,
Save the file.



Step 5 - View project in browser


Now goto your browser and navigate to your project url, eg -
http://localhost/[project-name]


Tada, you made it, the index.php is vanished from your urls... yippee!

0 comments:

Post a Comment