Include a clean url in Yii2

How to enable clean urls in Yii2. I want to remove index.php and '?' from URL parameters. Which section do you need to edit in Yii2 for this?

+60
clean-urls yii2 yii-url-manager
Oct 23 '14 at 9:42 on
source share
13 answers

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

 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 in the configuration 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>', ), ], 

For an advanced template create .htaccess inside the backend/web and frontend/web folders and add the urlManager component common/config/main.php

+148
Oct 24 '14 at 18:25
source share

The first important point is that

Module_Rewrite is enabled on your server (LAMP, WAMP, XAMP..etc). For URL redirection in yii2 environment. Create a single .htaccess file and put it in the / 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

The common/config/main-local.php added to the component 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>', ), ], 
+13
Apr 6 '15 at 23:02
source share

For me, the problem was this:

  • Missing .htaccess in the web folder as above.
  • The AllowOverride directive is set to None, which disables URL redirection. I changed it to All, and now beautiful URLs work well.
 <Directory "/path/to/the/web/directory/"> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> 
+13
May 01 '15 at 17:07
source share

First create .htaccess in the root folder in your Yii2 project with the following contents:

 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 the following contents:

frontend/web/ add backend/web/ Remember to add the .htaccess file to both web folders:

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



Now it is 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 administrator through

localhost/yii2project/backend/web

+9
Mar 20 '17 at 14:21
source share

on nginx is configured in this way

 location / { try_files $uri $uri/ /index.php$is_args$args; } 
+2
Aug 6 '16 at 16:31
source share

Just to add to this discussion - I 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 to the accepted answer, then just uncomment the above, the beautiful URLs will work (I have no idea what the “rules” are for in the accepted answer, but everything seems to work without them).

+2
Dec 13 '16 at 13:30
source share

Step 1: Put the .htaccess file in the 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 the .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 change to frontend/config/main.php . The following code should 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', ), ], 

The above steps work for me.

+1
Sep 14 '17 at 8:53 on
source share

What worked for me-
create .htaccess in the root folder of my Yii2 project and add the 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> 

New web folders for the .htaccess file have been created with the following contents:

 frontend/web/ 

and added the 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 should be in 'components' => [] .

Reboot my server and everything is working fine.

0
Aug 31 '17 at 13:58 on
source share

Step-by-step instruction

Step 1

At the root of the project, add .htaccess with the following contents:

 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 file, add the .htaccess file with the following contents:

 RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php 

Step 3

In the /config/web.php file in the elements of the array elements, add the following 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 ..

0
Nov 16 '17 at 11:39 on
source share

Step 1: in the config / main.php project, for example: frontend / config / main.php

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

Step 2: create a web folder with attached .htaccess files, for example: 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 
0
Apr 05 '18 at 7:59
source share

You only need to change two files: your .htaccess in backend / web and the common main file.

.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 

main.php

  'components' => [ 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => [ '<controller:\w+>/<action:\w+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<id:\d+>' => '<controller>/view', ], ], ], 
-one
Apr 05 '19 at 11:14
source share

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 
-2
Apr 18 '19 at
source share

I don’t know why you guys just don’t go to the yii2 provider folder and set the public $ enablePrettyUrl = true; "(along with changing htaccess, of course). It worked fine for me, and it's a lot easier. And I have one htaccess file - in the root of the project, and not in three different places. Also, when I did what you did, guys suggested for config / main.php programs in Advanced Yii2, it didn’t work I got 404s from ying-yang. I took it and prettyUrls did fine again. Maybe I should not do this because of the Composer update, but there is there are so many “fictitious” decisions that I'm tired of it.

-3
Sep 27 '17 at 19:12
source share



All Articles