This tutorial provides some insights into Apache configuration and Yii2 configuration in order to achieve user-friendly and search engine friendly URLs for your web app.
Yii2 official documentation has a page about Shared Hosting configuration that provides an example of how you can configure Apache for SEO friendly URLs using an .htaccess file.
Create a .htaccess file in your project root folder and put bellow code.
1 2 3 4 5 6 7 8 9 |
# prevent directory listings Options -Indexes IndexIgnore */* # follow symbolic links Options FollowSymlinks RewriteEngine on RewriteRule ^(.+)?$ web/$1 |
Create another .htaccess file in /web folder and put bellow code.
1 2 3 4 5 6 7 8 |
RewriteEngine on # If a directory or a file exists, use the request directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Otherwise forward the request to index.php RewriteRule . index.php |
After that you need to configure baseUrl & urlManager in your config/web.php file. We have to tell Yii that our base URL has changed. We do this by configuring baseUrl for urlManager and the request component in config/web.php.. Keep this two lines top of the page (config/web.php).
1 2 |
use \yii\web\Request; $baseUrl = str_replace('/web', '', (new Request)->getBaseUrl()); |
And finally set configuration (config/web.php) file like bellow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
'components' => [ 'request' => [ // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation 'cookieValidationKey' => 'your-value...', 'baseUrl' => $baseUrl, ], 'urlManager' => [ 'class' => 'yii\web\UrlManager', 'showScriptName' => false, // Disable index.php 'enablePrettyUrl' => true, // Disable r= routes 'suffix' => '.html', 'rules' => [ ], ], |