Enable clean URL in Yii2
Asked Answered
C

14

66

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?

Claw answered 23/10, 2014 at 9:42 Comment(3)
I recommedn to use Yii advanced improved for Yii2 projects as many of such issues are already resolved in it and it has many other things already done by the source providers. Just a suggestionNor
Take a look in here buddy github.com/kevingatp/Yii2-Pretty-URLCountercharge
It is basically all about mod_rewrite, well described in the Yii2 docs itself.Dipstick
C
159

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

Claw answered 24/10, 2014 at 18:25 Comment(6)
The rules you applied helped me, I tried without rules but always got error.Sugarplum
Ok, it seems this one is better. Just remember, that .htaccess file thing is only applicable if you are using apache - it's different with nginx and other web servers. I am deleting the second (mine) answer.Counterintelligence
Sometimes controllers and actions have a dash - character. I had to change \w+ to [\w\-]+ to get it to work with those.Knowland
Thank you for adding the answer for an advanced templateSells
@YasinPatel You are right it's not working for advanced template. Suggest any other solution for advanced template.Higgs
To install mod_rewrite:sudo a2enmod rewriteSimsar
I
17

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>',
   ),
],
Iyeyasu answered 6/4, 2015 at 23:2 Comment(1)
When you have hyphens/dashes in the controller and action names you need to replace \w+ with [\w\-]+.Huygens
F
15

First, create a .htaccess at root folder in your Yii2 project with following content:

Options +Indexes

<IfModule mod_rewrite.c> 
  RewriteEngine on

  RewriteCond %{REQUEST_URI} !^public
  RewriteRule ^(.*)$ frontend/web/$1 [L] 
</IfModule>

# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>

# Deny accessing dot files
RewriteRule (^\.|/\.) - [F]

Create another .htaccess file in your web folders with following content:

frontend/web/ add backend/web/ Don't forget to add .htaccess file to both web folders:

RewriteEngine on

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

RewriteRule . index.php

Now It's done. Change your URL configuration in Yii2:

<?php

use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());


$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'aiJXeUjj8XjKYIG1gurMMnccRWHvURMq',
            'baseUrl' => $baseUrl,
        ],
         "urlManager" => [
            'baseUrl' => $baseUrl,
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            "rules" => [
                "home" => "site/index",
                "about-us" => "site/about",
                "contact-us" => "site/contact",
            ]
        ]
    ],
];

return $config;

Your URL will change to:

localhost/yii2project/site/about => localhost/yii2project/about-us localhost/yii2project/site/contact => localhost/yii2project/contact-us localhost/yii2project/site/index => localhost/yii2project/home

You can access your admin through

localhost/yii2project/backend/web

Farrah answered 20/3, 2017 at 14:21 Comment(1)
After these confuguration in server also we need to enable mod_rewrite. In terminal run these commands sudo a2enmod rewrite , sudo service apache2 restart Now go to “/etc/apache2/apache2.conf” open it your favorite editor and change "AllowOverride none" to "AllowOverride All" save your changes and you need to restart Apache again by above command. File will be on readonly mode. So ensure the root login so add "su" command first su , vim /etc/apache2/apache2.conf, sudo service apache2 restart tutsnare.com/remove-index-php-from-url-in-yii2Aberrant
L
14

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>
Labret answered 1/5, 2015 at 17:7 Comment(1)
FollowSymLinks MultiViews this line made syntax error in the config file for me and I had to make it like this Options Indexes FollowSymLinksOba
L
3

on nginx configure like that

location / {
    try_files $uri $uri/ /index.php$is_args$args;
}
Leibniz answered 6/8, 2016 at 16:31 Comment(2)
If i did change in default.conf and then browse the url "IP/backend/web/site/login" then it show me the page "IP" but not my backend login, any idea?Interosculate
just did two locations to advanced yii2 app. Separate backend from frontend. And do for backend "root IP/backend/web;" and for frontend "root IP/frontend/web;" in your default.conf fileLeibniz
W
3

Just to add to this discussion - I've just installed Yii2, and it includes the following commented-out code in config/web.php:

'urlManager' => [
  'enablePrettyUrl' => true,
  'showScriptName' => false,
  'rules' => [],
],

If you add the .htaccess file in the accepted answer, then just uncomment the above, pretty URLs will work (I have no idea what the "rules" in the accepted answer are for, but everything seems to work without them).

Whisker answered 13/12, 2016 at 13:30 Comment(0)
C
1

Step 1: Put .htaccess file in root.

Options –Indexes

<IfModule mod_rewrite.c> 
  RewriteEngine on

  RewriteCond %{REQUEST_URI} !^public
  RewriteRule ^(.*)$ frontend/web/$1 [L] 
</IfModule>

# Deny accessing below extensions
<Files ~ "(.json|.lock|.git)">
Order allow,deny
Deny from all
</Files>

# Deny accessing dot files
RewriteRule (^\.|/\.) - [F]

Step 2: Put .htaccess file in frontend/web.

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

Step 3: Then changes in frontend/config/main.php. Following code need to be added inside 'components' => [].

'request' => [
 'csrfParam' => '_csrf-frontend',
 'baseUrl' => '/yii-advanced', //http://localhost/yii-advanced
],

'urlManager' => [
  'class' => 'yii\web\UrlManager',
  'showScriptName' => false, // Disable index.php
  'enablePrettyUrl' => true, // Disable r= routes
  'rules' => array(
          'about' => 'site/about',
          'service' => 'site/service',
          'contact' => 'site/contact',
          'signup' => 'site/signup',
          'login' => 'site/login',
  ),
],

Above steps are worked for me.

Creepy answered 14/9, 2017 at 8:53 Comment(0)
T
0

What worked for me-
create a .htaccess at root folder of my Yii2 project, and added following-

<IfModule mod_rewrite.c>
    Options +FollowSymlinks
    RewriteEngine On
</IfModule>

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_URI} ^/.*
    RewriteRule ^(.*)$ web/$1 [L]

    RewriteCond %{REQUEST_URI} !^/web/
    RewriteCond %{REQUEST_FILENAME} !-f [OR]
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^.*$ web/index.php
</IfModule>

Created new .htaccess file web folders with following content:

frontend/web/

and added following-

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

Then added urlmanager here-

projectFolder/common/config/main.php

For me it was not there, so added this as-

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

    ],*/
],

Make sure this code must be in 'components' => [].

Restart my server and everything works fine.

Thief answered 31/8, 2017 at 13:58 Comment(0)
V
0

Step-by-step instruction

Step 1

At the root of the project add a .htaccess with the following content:

Options +FollowSymLinks
IndexIgnore */*
RewriteEngine On
     RewriteCond %{REQUEST_URI} !^/(web)
    RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
    RewriteRule ^css/(.*)$ web/css/$1 [L]
    RewriteRule ^js/(.*)$ web/js/$1 [L]
    RewriteRule ^images/(.*)$ web/images/$1 [L]
    RewriteRule (.*) /web/$1
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /web/index.php

Step 2

In the folder /web add a .htaccess file with the following content:

RewriteEngine On RewriteBase /

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

RewriteRule . index.php

Step 3

In the file /config/web.php in element components of array add folowing code:

'request' => [
    // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
    'cookieValidationKey' => 'yYy4YYYX8lYyYyQOl8vOcO6ROo7i8twO',
    'baseUrl' => ''
],

//...

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '' => 'site/index',                                
        '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
    ],
],

Done..

Valuable answered 16/11, 2017 at 11:39 Comment(0)
M
0

Step1: in project config/main.php eg: frontend/config/main.php

'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [],
        ]

Step2: create .htaccess file inset web folder eg: frontend/web

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

#php_flag  display_errors        on
#php_value error_reporting       2039
Mystique answered 5/4, 2018 at 7:59 Comment(0)
S
0

Just add below code to your config file.

'urlManager' => [
    'enablePrettyUrl' => true,
    'rules' => [
        // your rules go here
    ],
    // ...
]
Sergent answered 22/12, 2020 at 6:39 Comment(0)
E
0

if you have installed yii2 application theme
go to basic/web/
inside -> .htaccess "paste code below if not exist"

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

then go to config/
inside web.php uncomment line starting from 47 to 52 (lines may be changed) or something similar to this..

'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
        ],
    ],
Esbensen answered 22/4, 2021 at 2:12 Comment(0)
V
0

I installed a new version of this framework.

In backend/config/main.php, you can see the code that is commented you can use this and do this for the frontend folder`.

Valma answered 20/9, 2021 at 7:58 Comment(0)
Y
-3

config/web.php

$params = require __DIR__ . '/params.php';
$db = require __DIR__ . '/db.php';


$config = [
'id' => 'basic',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'aliases' => [
'@bower' => '@vendor/bower-asset',
'@npm'   => '@vendor/npm-asset',
],
'components' => [
'assetManager' => [
// override bundles to use local project files :
'bundles' => [
'yii\bootstrap4\BootstrapAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'css' => [
YII_ENV_DEV ? 'css/bootstrap.css' : 'css/bootstrap.min.css',
],
],
'yii\bootstrap4\BootstrapPluginAsset' => [
'sourcePath' => '@app/assets/source/bootstrap/dist',
'js' => [
YII_ENV_DEV ? 'js/bootstrap.js' : 'js/bootstrap.min.js',
]
],
],
],

'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'V_Pj-uMLTPPxv0Be5Bwe3-UCC6EjGRuH',
'baseUrl' => '',
],

'formatter' => [
'dateFormat' => 'dd/MM/yyyy',
'decimalSeparator' => ',',
'thousandSeparator' => '.',
'currencyCode'      => 'BRL',
'locale'        => 'pt-BR',
'defaultTimeZone'   => 'America/Sao_Paulo',
'class'         => 'yii\i18n\Formatter',
],
'datehelper' => [
'class' => 'app\components\DateBRHelper',
],
'formatcurrency' => [
'class' => 'app\components\FormatCurrency',
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => '123456',

],
'cache' => [
'class' => 'yii\caching\FileCache',
],
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'mailer' => [
'class' => 'yii\swiftmailer\Mailer',
// send all mails to a file by default. You have to set
// 'useFileTransport' to false and configure a transport
// for the mailer to send real emails.
'useFileTransport' => true,
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'db' => $db,

'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'enableStrictParsing' => true,
'rules' => [
'' => 'site/index',                                
'<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
],
],

],
'params' => $params,
];

if (YII_ENV_DEV) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = [
'class' => 'yii\debug\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];

$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = [
'class' => 'yii\gii\Module',
// uncomment the following to add your IP if you are not connecting from localhost.
//'allowedIPs' => ['127.0.0.1', '::1'],
];
}

return $config; 

arquivo .htaccess na pasta raiz

<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
</IfModule>
<IfModule mod_rewrite.c>
RewriteCond %{REQUEST_URI} ^/.*
RewriteRule ^(.*)$ web/$1 [L]
RewriteCond %{REQUEST_URI} !^/web/
RewriteCond %{REQUEST_FILENAME} !-f [OR]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ web/index.php
</IfModule>

.htaccess dentro da pasta web/

RewriteEngine on

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

RewriteRule . index.php 
Youngling answered 18/4, 2019 at 0:8 Comment(1)
Thanks for contributing on StackOverflow. Please use English here.Lighterman

© 2022 - 2024 — McMap. All rights reserved.