Skip to content

How to remove index.php from URL in Yii2

Last updated on December 2, 2022

To remove the index.php, create a file called .htaccess at the root/web/ of your YII2 site. You can find out more about .htaccess here, but for our purposes here we just want to use it to hide index.php in our URLs. Not every web server is the same, but something along these lines should work for your purposes. Make sure you have mod_rewrite enabled it on your server.

.htaccess file :

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

Now go to config/web.php add edit urlManager configurations under the components section.

 'urlManager' => [
    'class' => 'yii\web\UrlManager',
    'showScriptName' => false,
    'enablePrettyUrl' => true,
    'rules' => array(
          '<controller:\w+>/<id:\d+>' => '/view',
          '<controller:\w+>/<action:\w+>/<id:\d+>' => '/',
          '<controller:\w+>/<action:\w+>' => '/',
    ),
 ],
</action:\w+></controller:\w+></id:\d+></action:\w+></controller:\w+></id:\d+></controller:\w+>

Now browse your application and you will find a clean URL and index.php has been removed from the URL in your Yii2 application.

0 0 votes
Article Rating
Subscribe
Notify of
guest

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments