Problem:
When accessing the frontend or backend of a Yii2 application, the paths "frontend/web" and "backend/web" are visible in URLs, which can be undesired. This article provides a solution to completely hide these paths.
Solution:
Step 1: .htaccess in Root Folder
Create a .htaccess file in the root folder (advanced/) with the following content:
Options +FollowSymlinks RewriteEngine On # Admin 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] # Frontend 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] 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
Step 2: components/Request.php
Create components/Request.php 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>
Step 3: Frontend and Backend Main Configuration
In frontend/config/main.php and backend/config/main.php, add the following under the components array:
<code class="php">'request' => [ 'class' => 'common\components\Request', 'web' => '/frontend/web' ], 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, ],</code>
In backend/config/main.php, additionally set the adminUrl:
<code class="php">'request' => [ 'class' => 'common\components\Request', 'web' => '/backend/web', 'adminUrl' => '/admin' ], 'urlManager' => [ 'enablePrettyUrl' => true, 'showScriptName' => false, ],</code>
Step 4 (Optional): .htaccess in Web Directories
Create a .htaccess file in both the frontend/web and backend/web directories with the following:
RewriteEngine On RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /index.php?/ [L]
Result:
After these changes, you should be able to access your frontend at http://localhost/yii2app/ and your backend at http://localhost/yii2app/admin/ without seeing the frontend or backend paths in the URLs.
The above is the detailed content of How to Hide Frontend and Backend Paths in Yii2 with .htaccess?. For more information, please follow other related articles on the PHP Chinese website!