This tutorial will provide some insights into Apache configuration and Yii2 configuration in order to achieve user friendly and search engine friendly URLs for your web app.
Here i will discuss two way to achieve user friendly and search engine friendly URLs for your web application.
- First hide frontend/web and backend/web
- Second enable pretty URL
Hide frontend/web and backend/web
Create .htaccess file on the root directory with this content.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Options +FollowSymLinks RewriteEngine On # End the processing, if a rewrite already occurred RewriteRule ^(frontend|backend)/web/ - [L] # Handle the case of backend, skip ([S=1]) the following rule, if current matched RewriteRule ^backend(/(.*))?$ backend/web/$2 [S=1] # handle the case of frontend RewriteRule .* frontend/web/$0 # Uncomment the following, if you want speaking URL #RewriteCond %{REQUEST_FILENAME} !-f #RewriteCond %{REQUEST_FILENAME} !-d #RewriteRule ^([^/]+/web)/.*$ $1/index.php |
After that you need to configure urlManager in your frontend/config/main.php and backend/config/main.php file.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
'request'=>[ 'baseUrl'=>'', ], 'urlManager' => [ 'scriptUrl'=>'/', ], 'request'=>[ 'baseUrl'=>'/backend', ], 'urlManager'=>[ 'scriptUrl'=>'/backend/index.php', ], |
Enable Pretty URL
By Default YII Advanced url structures for frontend and backend are:
yii/index.php?r=controller/action
To make user friendly and SEO friendly url we would like to change frontend url to: yii/controller/action And backend url to: Yii/backend/controller/action For this we need to make following changes:
Step 1: Edit common/config/main.php as below(If not working means add in frontend/config/main.php and backend/config/main.php)
1 2 3 4 5 6 7 8 9 10 |
'urlManager' => [ 'class' => 'yii\web\UrlManager', 'enablePrettyUrl' => true, 'showScriptName' => false, 'rules' => array( '<controller:\w+>/<id:\d+>' => '<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>', '<controller:\w+>/<action:\w+>' => '<controller>/<action>', ), ], |
Step 2: Add following .htaccess file into frontend/web folder
1 2 3 4 5 6 7 8 9 10 11 |
RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php Step 3 :Add following .htaccess file into backend/web folder RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . index.php |