.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:

  1. Options +FollowSymLinks
  2. IndexIgnore */*
  3. RewriteEngine On
  4.  
  5. RewriteCond %{REQUEST_URI} !^/(web)
  6. RewriteRule ^assets/(.*)$ /web/assets/$1 [L]
  7. RewriteRule ^css/(.*)$ web/css/$1 [L]
  8. RewriteRule ^js/(.*)$ web/js/$1 [L]
  9. RewriteRule ^images/(.*)$ web/images/$1 [L]
  10. RewriteRule (.*) /web/$1
  11.  
  12. RewriteCond %{REQUEST_FILENAME} !-f
  13. RewriteCond %{REQUEST_FILENAME} !-d
  14. RewriteRule . /web/index.php

Step 2

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

  1. RewriteEngine On RewriteBase /
  2.  
  3. RewriteCond %{REQUEST_FILENAME} !-f
  4. RewriteCond %{REQUEST_FILENAME} !-d
  5.  
  6. RewriteRule . index.php

Step 3

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

  1. 'request' => [
  2. // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
  3. 'cookieValidationKey' => 'yYy4YYYX8lYyYyQOl8vOcO6ROo7i8twO',
  4. 'baseUrl' => ''
  5. ],
  6.  
  7. //...
  8.  
  9. 'urlManager' => [
  10. 'enablePrettyUrl' => true,
  11. 'showScriptName' => false,
  12. 'rules' => [
  13. '' => 'site/index',
  14. '<controller:\w+>/<action:\w+>/' => '<controller>/<action>',
  15. ],
  16. ],

Done.