Skip to main content

Yii2 : hide /frontend/web in url addresses on apache

There is an issue on Yii2 to redirecting / urls to /frontend/web.
In other words we need a way to hidden /frontend/web from addresses.
We will do this without changing Apache configuration and creating virtual host or setting document root (It's good for share hostings that we have not access to apache.conf)
Let's do it:
1- Create .htaccess file on the root directory with this content
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]
2- Create .htaccess file in frontend/web with the below contents
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d 

RewriteRule . index.php
3- Now, we should play a little with frontend config of framework
You must open the frontend/config/main.php file and set $baseUrl for \yii\web\Request and \yii\web\urlManager.
$baseUrl is the url your application point to. if you host your application in the root directory of www you may set the $baseUrl to '/'
For another example if you are developing a blog system and your application hosted in www/blog you must set the baseUrl to '/blog' 
<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);
 
 
return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
 
    'components' => [
 
        'request' => [
            'baseUrl' => '/',
        ],
 
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
 
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
 
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
 
        'urlManager' => [
            'baseUrl' => '/',
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => []
        ]
    ],
    'params' => $params,
];

Soft Way 

If you not sure where your application will host, you must do it in pragmatically way. for this purpose we change the config file as below
<?php
$params = array_merge(
    require(__DIR__ . '/../../common/config/params.php'),
    require(__DIR__ . '/../../common/config/params-local.php'),
    require(__DIR__ . '/params.php'),
    require(__DIR__ . '/params-local.php')
);
 
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
 
return [
    'id' => 'app-frontend',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'controllerNamespace' => 'frontend\controllers',
 
    'components' => [
 
        'request' => [
            'baseUrl' => $baseUrl,
        ],
 
        'user' => [
            'identityClass' => 'common\models\User',
            'enableAutoLogin' => true,
        ],
 
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
            ],
        ],
 
        'errorHandler' => [
            'errorAction' => 'site/error',
        ],
 
        'urlManager' => [
            'baseUrl' => $baseUrl,
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => []
        ]
    ],
    'params' => $params,
];
As you see above we use \yii\web\Request to find $baseUrl of application. but because the returned $baseUrl contains /frontend/web we remove it
use \yii\web\Request;
$baseUrl = str_replace('/frontend/web', '', (new Request)->getBaseUrl());
sumber: Yiiframework.com

Comments

Popular posts from this blog

Format tanggal dan jam pada bahasa pemrograman PHP (Date Format)

PHP (PHP: Hypertext Processor) Merupakan salah satu bahasa pemrograman yang sangat dikenal di kalangan programer. dan versi PHP paling terbaru pada tahuin postingan ini dibuat adalah versi 7.3. Artikel kali ini berkaitan dengan salah satu parameter pada fungsi yang sering digunakan untuk menampilkan maupun memformat output tanggal dan jam (waktu). beberapa fungsi yang sering digunakan diantaranya date() dan date_format(). Fungsi date() fungsi date() umumnya digunakan untuk mengambil waktu dari sytem / waktu server. fungsi date memiliki beberapa parameter diantaranya: $format: Digunakan untuk menentukan bentuk output waktu yang di inginkan. $timestamp:  (Opsional)  Nilai satuan waktu dalam UNIX sytem , bertipedata integer. Fungsi date_format() fungsi date_format() adalah fungsi untuk merubah bentuk output dari variable yang bertipedata date. fungsi ini biasanya didahului dengan fungsi date_create(),   yaitu salah satu fungsi php yang membuat...

Merubah Folder Publik Pada Laravel 5.8

Laravel merupakan salah satu framework yang saat ini sedang ramai digunakan, Laravel memiliki struktur direktori / folder yang cukup mudah dipahami bahkan kita bisa membuat custom folder sendiri sesuai keperluan. Kali ini saya ingin berbagi hal yang saya dapat setelah mempelajari laravel dan berkeliling dari situs ke situs. yaitu bagaimana merubah folder publik pada laravel (saya menggunakan laravel v5.8). Sebagai Catatan umumnya setiap webserver selalu mencari & membaca terlebih dahulu file index pada publik direktori (folder) pada website. dan pada laravel terletak pada folder public.  Berikut Contoh struktur folder pada laravel : / /app /bootstrap /config /database /public     /index.php /resources /routes /storage Namaun pada saat kita akan mengupload / deploy website kita ke server Hosting yang pada umumnya menggunakan nama folder public_html . tentu suatu hal yang mungkin membuat kita sedikit bingung untuk merubah nama folder dari project kita ka...

Struktur dasar penuliasan tag HTML

Dalam membangun sebuah website ada hal hal yang perlu kamu pelajari dan mengerti. salah satunya penyusunan script atau tulisan kode penyusun halaman website kamu HTML ( Hyper Text Markup Language ) merupakan bahasa markah yang menyusun sebuah halaman website. Penulisan bahasa HTML diapit dengan tag < ... >  . Contohnya :  < H1 > ( kontent atau teks ) </H1>