.htaccess for Yii 2 basic

April 26, 2016 127 Yehor Rykhnov

Setting .htaccess for Yii2 basic. Or how to remove web from the URL in Yii 2 basic.

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.