Install Unite CMS on Heroku

Publié le June 7, 2019
Auteur: Alan Pilloud

Don't symlink assets

Each time you deploy to Heroku, a new build is made. The composer.json file is read and executed.

In the original composer.json file, you'll find a scripts section containing two scripts :

...

"scripts": {
    "post-install-cmd": [
        "bin/console assets:install --symlink"
    ],
    "post-update-cmd": [
        "bin/console assets:install --symlink"
    ]
}

...

This can't work as Symfony will use file_exists to check for existing assets. file_exists can't find symlinked files.

Remove the --symlink option and add --env=prod :

...

"scripts": {
    "post-install-cmd": [
        "Companienv\\Composer\\ScriptHandler::run",
        "bin/console assets:install --env=prod"
    ],
    "post-update-cmd": [
        "Companienv\\Composer\\ScriptHandler::run",
    "bin/console assets:install --env=prod"
    ]
}

...

Trust the proxy

Each Heroku Dyno sits behind a load balancer Read more on this topic here.

From this page :

Heroku’s HTTP Routing routes each request through a layer of reverse proxies which are, among other things, responsible for load balancing and terminating SSL connections. This means that requests received by a dyno will have the last router’s IP address in the REMOTE_ADDR environment variable, and the internal request will always be made using the HTTP protocol, even if the original request was made over HTTPS.
Like most common load balancers or reverse proxies, Heroku provides the original request information in X-Forwarded-… headers (as documented here). Symfony can easily be configured to trust such headers.

However, the proxy IP is not fixed, so you can't use the TRUSTED_PROXY environment variable.

Here is what I did :

in public/index.php

replace at line 27

if ($trustedProxies = $_SERVER['TRUSTED_PROXIES'] ?? false) {
    Request::setTrustedProxies(explode(',', $trustedProxies), Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST);
}

with

Request::setTrustedProxies(
    [$request->server->get('REMOTE_ADDR')],
    Request::HEADER_X_FORWARDED_ALL ^ Request::HEADER_X_FORWARDED_HOST
);

and move this line before the previous modification :

$request = Request::createFromGlobals();