Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable clean URL in Yii2

How can I enable clean urls in Yii2. I want to remove index.php and '?' from url parameters. Which section needs to be edited in Yii2 for that?

like image 730
user7282 Avatar asked Oct 23 '14 09:10

user7282


3 Answers

I got it working in yii2. Enable mod_rewrite for Apache. For basic template do the following: Create a .htaccess file in web folder and add this

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

Then inside config folder, in web.php add to components

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

In the case of advanced template create the .htaccess files inside backend/web and frontend/web folders and add urlManager component inside common/config/main.php

like image 59
user7282 Avatar answered Oct 20 '22 09:10

user7282


First important point is that

Module_Rewrite is enabled on your server(LAMP,WAMP,XAMP..etc) For do URL rewiring in yii2 framework Create one .htaccess file and put in /web folder

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

Second step

Config folder common/config/main-local.php add to components array

'urlManager' => [
   'class' => 'yii\web\UrlManager',
   // Disable index.php
   'showScriptName' => false,
   // Disable r= routes
   'enablePrettyUrl' => true,
   'rules' => array(
      '<controller:\w+>/<id:\d+>' => '<controller>/view',
      '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
      '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
   ),
],
like image 41
Sijo Thomas Maprayil Avatar answered Oct 20 '22 08:10

Sijo Thomas Maprayil


For me, the problem was:

  1. Missing .htaccess in the web folder just like mentioned above.
  2. The AllowOverride directive was set to None, which disabled URL rewrites. I changed it to All and now pretty URLs work nicely.
<Directory "/path/to/the/web/directory/">
  Options Indexes 
  FollowSymLinks MultiViews 
  AllowOverride All 
  Require all granted
</Directory>
like image 14
pkout Avatar answered Oct 20 '22 09:10

pkout