Home >Backend Development >PHP Tutorial >How to Hide the Frontend and Backend Directories from URLs in a Yii2 Website?
Hiding frontend/web and backend/web Directories on Yii2 Websites with .htaccess
Problem:
In the Yii2 Advanced template, the frontend and backend directories can be seen in the website's URLs. This can be undesirable for a more professional or customized appearance.
Solution:
To hide these directories, modify the .htaccess file in the website's root directory as follows:
Options +FollowSymlinks RewriteEngine On # Handle admin URL separately RewriteCond %{REQUEST_URI} ^/(admin) RewriteRule ^admin/assets/(.*)$ backend/web/assets/ [L] RewriteRule ^admin/css/(.*)$ backend/web/css/ [L] RewriteCond %{REQUEST_URI} !^/backend/web/(assets|css)/ RewriteCond %{REQUEST_URI} ^/(admin) RewriteRule ^.*$ backend/web/index.php [L] # Handle frontend assets RewriteCond %{REQUEST_URI} ^/(assets|css) RewriteRule ^assets/(.*)$ frontend/web/assets/ [L] RewriteRule ^css/(.*)$ frontend/web/css/ [L] RewriteRule ^js/(.*)$ frontend/web/js/ [L] RewriteRule ^images/(.*)$ frontend/web/images/ [L] # Handle frontend RewriteCond %{REQUEST_URI} !^/(frontend|backend)/web/(assets|css)/ RewriteCond %{REQUEST_URI} !index.php RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^.*$ frontend/web/index.php
Additional Configuration:
For proper URL handling, create a components/Request.php file in the common directory and add the following code:
<code class="php">namespace common\components; class Request extends \yii\web\Request { public $web; public $adminUrl; public function getBaseUrl() { return str_replace($this->web, "", parent::getBaseUrl()) . $this->adminUrl; } public function resolvePathInfo() { if ($this->getUrl() === $this->adminUrl) { return ""; } else { return parent::resolvePathInfo(); } } }</code>
Configure the Request component in frontend/config/main.php and backend/config/main.php, respectively:
<code class="php">// frontend 'request' => [ 'class' => 'common\components\Request', 'web' => '/frontend/web' ], // backend 'request' => [ 'class' => 'common\components\Request', 'web' => '/backend/web', 'adminUrl' => '/admin' ],</code>
Additional .htaccess Configuration for Web Directory:
If the above steps do not resolve the issue, create or modify the .htaccess file in the web directory (both frontend and backend) with the following contents:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/ [L]
After implementing these configurations, the website's URLs will no longer display the frontend/web or backend/web directories, providing a cleaner and more professional appearance.
The above is the detailed content of How to Hide the Frontend and Backend Directories from URLs in a Yii2 Website?. For more information, please follow other related articles on the PHP Chinese website!