Search code examples
apacheweb-deploymentyii2

Deploying a Yii 2 app to a subdirectory of the document root


I want to deploy a Yii 2 app to a website's subdirectory:

http://example.com/subdirectory

My app's directory structure looks like this:

|-- LICENSE.md
|-- README.md
|-- assets
|-- commands
|-- components
|-- composer.json
|-- composer.lock
|-- config
|-- controllers
|-- mail
|-- models
|-- requirements.php
|-- runtime
|-- test.php
|-- test.txt
|-- tests
|-- vendor
|-- views
|-- web
|-- yii
`-- yii.bat

According to Yii 2's documentation, for deployment you're supposed to rename the web folder to the document root of your server, like public_html, wwww, etc. Then you copy all the files to the parent directory of the document root. But nothing is said about how to deploy the app to a subdirectory of the document root.

The host is Apache, and I'm wondering if using an alias is the easiest way. I'm not sure from the documentation on mod_alias which directive to use or where it should go, though.

What do you recommend?


Solution

  • It turned out to be simpler than I expected.

    1. Move the web directory into your document root (e.g., public_html, www, etc.).
    2. Rename the web directory how you want to appear after the domain name. For instance, if you want your app to live at http://example.com/myapp, then rename web to myapp.
    3. Move your app's directory (which now should be minus the web subdirectory) one directory above your document root.
    4. In the web directory, change the paths of the three require functions in index.php.

    My modified index.php looks similar to the below. (If you copy and paste, remember to replace your_app_name with the name of your app's directory. Also note that I have multiple websites in my document root, so I have to get the parent of the parent of the parent of the web folder to make it out of the document root. Whew.)

    <?php
    
    // comment out the following two lines when deployed to production
    defined('YII_DEBUG') or define('YII_DEBUG', true);
    defined('YII_ENV') or define('YII_ENV', 'dev');
    
    require(__DIR__ . '/../../../your_app_name/vendor/autoload.php');
    require(__DIR__ . '/../../../your_app_name/vendor/yiisoft/yii2/Yii.php');
    
    $config = require(__DIR__ . '/../../../your_app_name/config/web.php');
    
    (new yii\web\Application($config))->run();